diff --git a/README.md b/README.md index 38bc61d..8ef99f0 100644 --- a/README.md +++ b/README.md @@ -172,11 +172,13 @@ would format — same walk, same `--exclude`, same `.gitignore` handling, same `lucisv.toml` discovery. ```bash -lucisv check rtl/ # FILE:LINE:COL: message [rule-name] +lucisv check rtl/ # FILE:LINE:COL: severity: message [rule] lucisv check --output-format json rtl/ # one JSON array, for editors and CI lucisv check --select no-tabs rtl/ # only these rules (comma-separated) lucisv check --ignore module-filename rtl/ # everything but these +lucisv check --select error rtl/ # a whole severity class, by name lucisv check --fix rtl/ # apply the safe fixes, write files back +lucisv check --rules-doc # the generated reference for every rule ``` Exit codes are the frozen contract above: 0 clean (or everything fixed), 1 @@ -184,28 +186,84 @@ violations remain, 2 error. Unlike the formatter, `check` uses the error-tolerant parser, so a file lucisv cannot fully parse is still linted for what it can see. -| Rule | Fix | What it wants | +### Severities + +Every rule is in one of three classes, and the class is the word that stands +in the diagnostic line, in the JSON `severity` field, and in the editor's +squiggle colour: + +| Class | Means | Editor | |---|---|---| -| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) | -| `no-trailing-whitespace` | safe | nothing but code before the newline | -| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` | -| `always-ff-non-blocking` | — | `<=` inside `always_ff` | -| `always-comb-blocking` | — | `=` inside `always_comb` | -| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` | -| `module-filename` | — | a one-module file is named after its module | -| `unused-waiver` | — | waivers that suppress nothing | -| `unused-signal` † | — | no net or variable nothing uses | -| `undriven-net` † | — | everything read is driven by something | -| `multiply-driven` † | — | one driver per variable | +| `error` | would very likely fail to compile, elaborate or synthesize | red (LSP Error) | +| `warning` | compiles, and very likely does not mean what it says | yellow (LSP Warning) | +| `style` | correct, and reads badly | blue (LSP Information) | + +A class name is accepted **wherever a rule name is** — on `--select`, on +`--ignore`, and in `select`/`ignore` under `[lint]` in `lucisv.toml`: + +```bash +lucisv check --select error rtl/ # only the compile-breakers +lucisv check --ignore style rtl/ # everything but the naming rules +``` + +Every `error`-class rule follows one discipline: **silence beats a wrong +accusation**. Each of them goes quiet whenever the run cannot answer — a file +that did not fully parse, a module the project does not hold or holds twice, a +name a macro produces, a fragment written to be `` `include``d. That is what +makes an editor's red squiggle worth believing. + +### The rules + +| Rule | Severity | Fix | What it wants | +|---|---|---|---| +| `multiply-driven` † | error | — | one driver per variable | +| `wire-reg-mixup` | error | — | `logic`, not `reg`, in a `.sv` file | +| `mismatched-labels` | error | — | `end : name` names the block it closes | +| `duplicate-declaration` | error | — | each name declared once per scope | +| `undeclared-identifier` † | error | — | every name is declared somewhere in the project | +| `unknown-port` † | error | — | `.name(…)` is a port the module declares | +| `unknown-parameter` † | error | — | `#(.NAME(…))` is a parameter it declares | +| `always-ff-non-blocking` | warning | — | `<=` inside `always_ff` | +| `always-comb-blocking` | warning | — | `=` inside `always_comb` | +| `case-missing-default` | warning | — | every `case`/`casex`/`casez` has a `default` | +| `incomplete-assignment` | warning | — | an `always_comb` assigns on every path | +| `suspicious-semicolon` | warning | — | no `if (x);` / `for (…);` / `while (…);` | +| `forbid-defparam` | warning | — | override at the instantiation, not with `defparam` | +| `invalid-system-task-function` | warning | — | no `$random`, `$psprintf`, `$dist_*`, `$srandom` | +| `plusarg-assignment` | warning | — | `$value$plusargs`, not `$test$plusargs` | +| `truncated-numeric-literal` | warning | — | a sized literal fits its width | +| `undersized-binary-literal` | warning | safe | every bit of a sized binary literal is written | +| `packed-dimensions-range-ordering` | warning | — | a packed dimension is `[N-1:0]` | +| `forbid-negative-array-dim` | warning | — | no negative literal in a dimension | +| `module-port` | warning | — | more than one port is connected by name | +| `module-parameter` | warning | — | more than one parameter is overridden by name | +| `explicit-function-task-parameter-type` | warning | — | every tf argument has a storage type | +| `void-cast` | warning | — | `void'(…)` wraps a call | +| `instance-shadowing` | warning | — | no declaration hides an enclosing one | +| `undriven-net` † | warning | — | everything read is driven by something | +| `unused-signal` † | warning | — | no net or variable nothing uses | +| `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) | +| `no-trailing-whitespace` | style | safe | nothing but code before the newline | +| `empty-item` | style | safe | no `;` standing where an item belongs | +| `explicit-parameter-storage-type` | style | — | `parameter int W = 8`, not `parameter W = 8` | +| `module-filename` | style | — | a one-module file is named after its module | +| `enum-name-style` | style | — | `lower_snake_case` ending `_e`/`_t` | +| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` | +| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` | +| `module-name-style` | style | — | `lower_snake_case` (off by default) | +| `unused-waiver` | style | — | waivers that suppress nothing | † On by default when lucisv can see a project (a multi-file CLI run or the language server), and off for a single file or stdin unless `--select` names -them. These three read the file's *symbol table*, not just its syntax; the -project-wide identifier census keeps a hierarchical use in another file from -becoming a false positive. See `docs/features/semantic-lints-on/README.md`. -The table above is not the whole set — naming-style rules ship too, and -`cargo run -p vlog_linter --example rules_markdown` prints the generated -reference for every rule with its default. +them. These rules read the file's *symbol table* and ask the project about +names, not just the file's syntax; the project-wide identifier census keeps a +hierarchical use in another file from becoming a false positive. See +`docs/features/semantic-lints-on/README.md` and +`docs/features/linter-expansion-1/README.md`. + +`lucisv check --rules-doc` prints the whole reference — every rule, its class, +its default, its fix and the paragraph saying why it exists — generated from +the registry, so it can never be out of date. Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those that cannot change what the code means), `--unsafe-fixes` widens that — no diff --git a/TODO.md b/TODO.md index 1ae47b2..4d240a4 100644 --- a/TODO.md +++ b/TODO.md @@ -3623,17 +3623,17 @@ additive, say so in Handshakes), crates/lucisv/src/{lint.rs, args.rs} editors/vscode/{package.json, README.md}, README.md "Linting", docs/site/src/content/docs/reference/rules.md, docs/features/ linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`. -- [ ] 33.0 `Severity` on every rule; select/ignore by severity; CLI +- [x] 33.0 `Severity` on every rule; select/ignore by severity; CLI text/JSON; editor severities; `--rules-doc` grouped -- [ ] 33.1 package.json toggles generated + drift test; `enabled_rules` +- [x] 33.1 package.json toggles generated + drift test; `enabled_rules` precedence pinned; republish on change -- [ ] 33.2 Error rules: mismatched-labels, duplicate-declaration, +- [x] 33.2 Error rules: mismatched-labels, duplicate-declaration, undeclared-identifier (measured; default decided by the count), unknown-port, unknown-parameter -- [ ] 33.3 Warning rules: the thirteen listed, each with tests and an +- [x] 33.3 Warning rules: the thirteen listed, each with tests and an opentitan count -- [ ] 33.4 docs; measurements table in the README -- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820 +- [x] 33.4 docs; measurements table in the README +- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820 byte-identical (formatter untouched); opentitan read-only `lucisv check` census + timing - [ ] QA: every new rule attacked with hand-written true positives and diff --git a/crates/lucisv/src/lint.rs b/crates/lucisv/src/lint.rs index d57dceb..6b1c7ca 100644 --- a/crates/lucisv/src/lint.rs +++ b/crates/lucisv/src/lint.rs @@ -50,6 +50,11 @@ pub struct Plan { /// a rule asks about one name at a time and never about a file. pub struct Census { files: HashMap, + /// Module or interface name → what it declares, `None` for a unit the run + /// cannot answer for: a header carrying a compiler directive, or two + /// declarations that disagree. Empty when no enabled rule asked for it — + /// building it costs a parse of every file in the run. + interfaces: HashMap>, } impl Census { @@ -58,27 +63,61 @@ impl Census { /// A file that cannot be read or does not lex contributes nothing, which /// is the same all-or-nothing rule the rest of the run gives it: the /// file's own check reports the error. - fn of(jobs: &[Job]) -> Census { - let per_file: Vec> = jobs + /// + /// `interfaces` says whether the run also needs each unit's ports and + /// parameters (`unknown-port`, `unknown-parameter`). It costs a **parse** + /// of every file on top of the lex the word census already pays for, so + /// it is built only when some enabled rule asks — measured on opentitan + /// `hw/` in `docs/features/linter-expansion-1/README.md`. + fn of(jobs: &[Job], interfaces: bool) -> Census { + type PerFile = (Vec, Vec<(String, Option)>); + let per_file: Vec = jobs .par_iter() - .map(|job| match std::fs::read_to_string(&job.path) { - Ok(src) => words::harvest_text(&src), - Err(_) => Vec::new(), + .map(|job| { + let Ok(src) = std::fs::read_to_string(&job.path) else { + return (Vec::new(), Vec::new()); + }; + if !interfaces { + return (words::harvest_text(&src), Vec::new()); + } + // One lex for both halves: the parse is what the interface + // table needs, and its tokens are the word census's. + let parsed = ParsedSource::parse(&src); + (words::harvest(parsed.tokens()), vlog_linter::module_interfaces(parsed.file())) }) .collect(); + let mut files: HashMap = HashMap::new(); - for words in per_file { + let mut units: HashMap> = HashMap::new(); + for (words, declared) in per_file { for word in words { *files.entry(word).or_default() += 1; } + for (name, interface) in declared { + // Two declarations of one name answer only when they agree; + // anything else is a question the run cannot settle. + units + .entry(name) + .and_modify(|held| { + if *held != interface { + *held = None; + } + }) + .or_insert(interface); + } } - Census { files } + Census { files, interfaces: units } } /// How many files in the run write `name` down. fn count(&self, name: &str) -> u32 { self.files.get(name).copied().unwrap_or(0) } + + /// What the run says `name` declares, or `None` when it cannot say. + fn interface(&self, name: &str) -> Option { + self.interfaces.get(name)?.clone() + } } /// One file's view of the census: everything the project says, minus what @@ -96,6 +135,13 @@ impl MentionOracle for Elsewhere<'_> { let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok()); self.census.count(name) > mine } + + /// The run's interface table, which covers **every** file including this + /// one: a module is instantiated as often in the file that declares it as + /// anywhere else, and there is nothing to subtract here. + fn module_interface(&self, name: &str) -> Option { + self.census.interface(name) + } } /// Resolve the run: the rules for each file, and whether a census is owed. @@ -120,10 +166,25 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res jobs.push(Job { path, config, rules }); } let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace())); - let census = (workspace && wanted).then(|| Census::of(&jobs)); + let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule))); + let census = (workspace && wanted).then(|| Census::of(&jobs, workspace && interfaces)); Ok(Plan { jobs, census }) } +/// Whether this rule reads the census's **interface** half, which costs a +/// parse of every file in the run rather than a lex. +/// +/// By name, because the alternative is a fourth boolean on the `Rule` trait +/// for two rules: `Rule::needs_workspace` already says "this rule asks the +/// project something", and which *question* it asks is between the rule and +/// the oracle. A name that is not in the registry cannot reach here — the +/// rules are `&'static dyn Rule` values from that registry — and a rule added +/// to the pair without being added here answers `None` and goes quiet, which +/// is the safe direction. +fn reads_interfaces(rule: &'static dyn Rule) -> bool { + matches!(rule.name(), "unknown-port" | "unknown-parameter") +} + /// The command line's list when it said anything, else the config file's. fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] { if cli.is_empty() { @@ -348,15 +409,23 @@ fn finish(opts: &Options, reports: Vec) -> ExitCode { } } -/// Verible's diagnostic line: `FILE:LINE:COL: message [rule-name]`. +/// Verible's diagnostic line with the severity word in front of the message: +/// `FILE:LINE:COL: error|warning|style: message [rule-name]`. +/// +/// The word sits where a compiler puts it, so the line greps and reads the way +/// every other tool's does, and `grep ': error:'` is the whole of "show me +/// what would not compile". fn print_text(reports: &[Report]) { let mut out = String::new(); for report in reports { for violation in &report.violations { let (line, col) = position(report, violation); out.push_str(&format!( - "{}:{line}:{col}: {} [{}]\n", - report.path, violation.message, violation.rule + "{}:{line}:{col}: {}: {} [{}]\n", + report.path, + violation.severity.as_str(), + violation.message, + violation.rule )); } } @@ -372,12 +441,13 @@ fn print_json(reports: &[Report]) { let (line, col) = position(report, violation); let (end_line, end_col) = end_position(report, violation); items.push(format!( - "{{\"filename\":{},\"rule\":{},\"message\":{},\ + "{{\"filename\":{},\"rule\":{},\"severity\":{},\"message\":{},\ \"location\":{{\"line\":{line},\"column\":{col}}},\ \"end_location\":{{\"line\":{end_line},\"column\":{end_col}}},\ \"range\":{{\"start\":{},\"end\":{}}},\"fix\":{}}}", quote(&report.path), quote(violation.rule), + quote(violation.severity.as_str()), quote(&violation.message), violation.span.start, violation.span.end, diff --git a/crates/lucisv/tests/cli.rs b/crates/lucisv/tests/cli.rs index aec74b6..5c8a328 100644 --- a/crates/lucisv/tests/cli.rs +++ b/crates/lucisv/tests/cli.rs @@ -753,7 +753,9 @@ fn check_reports_violations_and_exits_1() { let out = run(&["check", &path]); assert_eq!(code(&out), 1, "violations must exit 1: {}", stderr(&out)); let text = stdout(&out); - assert!(text.contains(&format!("{path}:2:1: tab character")), "{text}"); + // `FILE:LINE:COL: severity: message [rule]` — the severity word is part + // of the line since §33.0, and both of these are style findings. + assert!(text.contains(&format!("{path}:2:1: style: tab character")), "{text}"); assert!(text.contains("[no-tabs]"), "{text}"); assert!(text.contains("[module-filename]"), "{text}"); assert!(stderr(&out).contains("found 2 violations"), "{}", stderr(&out)); @@ -797,6 +799,7 @@ fn check_json_is_one_array_with_positions_and_fixes() { assert!(text.starts_with('['), "{text}"); assert!(text.trim_end().ends_with(']'), "{text}"); assert_eq!(text.matches("\"rule\":\"no-tabs\"").count(), 1, "{text}"); + assert!(text.contains("\"severity\":\"style\""), "{text}"); assert!(text.contains("\"location\":{\"line\":2,\"column\":1}"), "{text}"); assert!(text.contains("\"applicability\":\"safe\""), "{text}"); assert!(text.contains("\"content\":\" \""), "{text}"); @@ -895,6 +898,30 @@ fn check_select_and_ignore_pick_the_rule_set() { assert!(stderr(&out).contains("unknown rule"), "{}", stderr(&out)); } +/// A severity word stands for its whole class wherever a rule name fits — +/// §33.0's headline for the command line. +#[test] +fn check_select_and_ignore_accept_a_severity_word() { + let dir = TempDir::new("check-severity"); + // `reg` is an error-class finding, the tab and the name are style ones. + let path = dir.write("bar.sv", "module foo;\n\treg a;\nendmodule\n"); + + let out = run(&["check", "--select", "error", &path]); + assert_eq!(code(&out), 1, "{}", stdout(&out)); + let text = stdout(&out); + assert_eq!(text.lines().count(), 1, "{text}"); + assert!(text.contains(": error: "), "{text}"); + assert!(text.contains("[wire-reg-mixup]"), "{text}"); + + let out = run(&["check", "--ignore", "style", &path]); + assert_eq!(stdout(&out).lines().count(), 1, "{}", stdout(&out)); + assert!(stdout(&out).contains("[wire-reg-mixup]"), "{}", stdout(&out)); + + // Ignoring every class leaves nothing to report. + let out = run(&["check", "--ignore", "error,warning,style", &path]); + assert_eq!(code(&out), 0, "{}", stdout(&out)); +} + #[test] fn check_honors_inline_waivers_and_reports_dead_ones() { let dir = TempDir::new("check-waive"); diff --git a/crates/lucisv_server/src/diagnostics.rs b/crates/lucisv_server/src/diagnostics.rs index 0d2a3fc..4f609c9 100644 --- a/crates/lucisv_server/src/diagnostics.rs +++ b/crates/lucisv_server/src/diagnostics.rs @@ -135,11 +135,12 @@ mod tests { #[test] fn one_list_carries_both_sources() { // A file that parses cleanly and violates a lint rule: the publish is - // one list, and the lint finding is in it as a warning. + // one list, and the lint finding is in it at its rule's own severity + // — `no-tabs` is a style rule, so INFORMATION (§33.0). let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n"); let published = all(ws.document(&uri).expect("open")); assert_eq!(published.len(), 1); - assert_eq!(published[0].severity, Some(DiagnosticSeverity::WARNING)); + assert_eq!(published[0].severity, Some(DiagnosticSeverity::INFORMATION)); assert_eq!(published[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into()))); } @@ -149,7 +150,7 @@ mod tests { let published = all(ws.document(&uri).expect("open")); let severities: Vec<_> = published.iter().map(|d| d.severity).collect(); assert!(severities.contains(&Some(DiagnosticSeverity::ERROR)), "{published:#?}"); - assert!(severities.contains(&Some(DiagnosticSeverity::WARNING)), "{published:#?}"); + assert!(severities.contains(&Some(DiagnosticSeverity::INFORMATION)), "{published:#?}"); assert!(published.iter().all(|d| d.source.as_deref() == Some("lucisv"))); // Errors first: a parse error is what the user must fix. assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR)); diff --git a/crates/lucisv_server/src/lint.rs b/crates/lucisv_server/src/lint.rs index cd2ef0e..838e88d 100644 --- a/crates/lucisv_server/src/lint.rs +++ b/crates/lucisv_server/src/lint.rs @@ -11,15 +11,19 @@ //! `docs/features/semantic-lints-on/README.md` and //! `docs/features/server-lint/README.md`. +use std::collections::BTreeSet; + use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString}; use vlog_formatter::fence::{self, Region}; use vlog_linter::{ - default_rules, lint, workspace_rules, LintContext, MentionOracle, Rule, Violation, + default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule, + Severity, Violation, }; -use vlog_semantic::{FileId, WorkspaceIndex}; +use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex}; use crate::convert::Positions; use crate::diagnostics::SOURCE; +use crate::settings::ClientSettings; use crate::state::{Document, Workspace}; /// What one lint pass runs: which rules, and what it may ask about the files @@ -52,12 +56,7 @@ impl<'a> 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 client = ws.client_settings(); - // Every name in the settings was checked against the registry when the - // settings were parsed, so this cannot fail; if it somehow does, the - // defaults are the answer a dropped setting always gets here. - let rules = vlog_linter::select_rules(&client.lint_select, &client.lint_ignore, workspace) - .unwrap_or_else(|_| if workspace { workspace_rules() } else { default_rules() }); + let rules = enabled_rules(ws.client_settings(), workspace); let oracle = workspace.then_some(IndexMentions { index, own }); LintRun { rules, oracle } } @@ -72,6 +71,63 @@ impl<'a> LintRun<'a> { } } +/// Which rules a buffer is linted with, given what the editor's settings 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; +/// 3. a `lucisv.lint.severity.` switched off **removes** every rule of +/// that class; +/// 4. a `lucisv.lint.rules.` 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. +/// +/// Rungs 2 and 5 accept a severity word wherever a rule name fits. +pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'static dyn Rule> { + let base = if settings.lint_select.is_empty() { + if has_oracle { + workspace_rules() + } else { + default_rules() + } + } else { + named(&settings.lint_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(&settings.lint_ignore) { + on.remove(rule.name()); + } + vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect() +} + +/// 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. /// @@ -97,6 +153,32 @@ 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 { + 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) + } } /// The document's own parse products, lent to the linter — "one parse, two @@ -175,14 +257,13 @@ pub fn diagnostics_in(doc: &Document, run: &LintRun) -> Vec { /// The diagnostic a violation becomes. /// -/// **Warning**, never Error: a lint finding is an opinion about style, and a -/// parse error is the compiler refusing. 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. +/// 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(DiagnosticSeverity::WARNING), + severity: Some(severity_of(violation.severity)), code: Some(NumberOrString::String(violation.rule.to_string())), source: Some(SOURCE.to_string()), message: violation.message.clone(), @@ -190,6 +271,21 @@ pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnosti } } +/// 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::*; @@ -211,13 +307,35 @@ mod tests { 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::WARNING)); + 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"); @@ -368,6 +486,121 @@ mod tests { 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() { + let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> { + enabled_rules(settings, 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::>() + ); + assert_eq!( + names(&base, true), + workspace_rules().iter().map(|r| r.name()).collect::>() + ); + + // 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] diff --git a/crates/lucisv_server/src/server/notification.rs b/crates/lucisv_server/src/server/notification.rs index 2cbd279..122181a 100644 --- a/crates/lucisv_server/src/server/notification.rs +++ b/crates/lucisv_server/src/server/notification.rs @@ -268,9 +268,13 @@ impl Server { /// The rule selection in force, as a value two settings pushes can be /// compared by. - fn lint_selection(&self) -> (Vec, Vec) { - let client = self.workspace.client_settings(); - (client.lint_select.clone(), client.lint_ignore.clone()) + /// + /// All four lint settings, not just the two lists: since §33.1 a class + /// switch (`lucisv.lint.severity.*`) and a per-rule toggle + /// (`lucisv.lint.rules.*`) change which rules run too, and a change to one + /// of them must republish exactly as a change to `select`/`ignore` does. + fn lint_selection(&self) -> settings::LintSelection { + settings::lint_selection(self.workspace.client_settings()) } } diff --git a/crates/lucisv_server/src/settings.rs b/crates/lucisv_server/src/settings.rs index 6e3254c..0672f9f 100644 --- a/crates/lucisv_server/src/settings.rs +++ b/crates/lucisv_server/src/settings.rs @@ -13,9 +13,11 @@ //! 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::collections::BTreeMap; use std::ops::RangeInclusive; use serde_json::Value; +use vlog_linter::Severity; /// Accepted `line-length`, and accepted `indent`. /// @@ -174,6 +176,20 @@ pub struct ClientSettings { /// `lucisv.lint.ignore`: rules dropped from whatever `select` left. Same /// validation, same reason. pub lint_ignore: Vec, + /// `lucisv.lint.severity.error` / `.warning` / `.style`: the master switch + /// of each class. Every class is present and `true` unless a client turned + /// one off — see `lint::enabled_rules` for where it sits in the ladder. + pub lint_severity: BTreeMap, + /// `lucisv.lint.rules.`: the rules a client said something + /// **explicit** about — `true` for `on`, `false` for `off`. + /// + /// A rule left at `default` is *absent from this map*, and that is the + /// whole reason the setting is a three-word enum rather than a boolean: a + /// client sends the whole section, every key at its default, so "unset" + /// and "set to the shipped value" would arrive identically and a per-rule + /// toggle nobody touched would silently override `select` and the class + /// switches. + pub lint_rules: BTreeMap, } /// The settings a client that said nothing is treated as having asked for. @@ -200,10 +216,35 @@ impl Default for ClientSettings { large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD, lint_select: Vec::new(), lint_ignore: Vec::new(), + lint_severity: every_class_on(), + lint_rules: BTreeMap::new(), } } } +/// Every severity class switched on — what a client that said nothing means. +fn every_class_on() -> BTreeMap { + Severity::ALL.into_iter().map(|severity| (severity, true)).collect() +} + +/// Everything about a settings value that decides **which rules run**: the two +/// name lists, the class switches and the per-rule toggles. +/// +/// Its only use is equality — the server compares it across a settings change +/// to decide whether every open file must be published again. +pub type LintSelection = + (Vec, Vec, BTreeMap, BTreeMap); + +/// The four lint settings of `settings`, as one comparable value. +pub fn lint_selection(settings: &ClientSettings) -> LintSelection { + ( + settings.lint_select.clone(), + settings.lint_ignore.clone(), + settings.lint_severity.clone(), + settings.lint_rules.clone(), + ) +} + /// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload. /// /// **Nothing here trusts the client.** `package.json`'s JSON schema constrains @@ -274,17 +315,53 @@ pub fn from_payload(settings: &Value) -> ClientSettings { .unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD), lint_select: rules(lint.and_then(|l| l.get("select"))), lint_ignore: rules(lint.and_then(|l| l.get("ignore"))), + // `lucisv.lint.severity.` and `lucisv.lint.rules.` nest + // one level deeper again, for the same reason `index.*` does. + lint_severity: severity_switches(lint.and_then(|l| l.get("severity"))), + lint_rules: rule_toggles(lint.and_then(|l| l.get("rules"))), } } -/// The rule names in a settings array, dropping every one the registry does -/// not know. +/// The rule names in a settings array, dropping every one that names neither a +/// rule nor a severity class. /// /// Silence rather than an error, on this module's standing rule: a push is /// JSON on a socket, and a typo in one name must not cost the user every /// diagnostic in the file. A dropped name leaves the rule where it was. fn rules(value: Option<&Value>) -> Vec { - strings(value).into_iter().filter(|name| vlog_linter::rule_by_name(name).is_some()).collect() + strings(value).into_iter().filter(|name| vlog_linter::rules_named(name).is_some()).collect() +} + +/// The three class master switches, each `true` unless a client turned it off. +/// +/// A missing or wrong-typed switch leaves its class on: the safe direction for +/// a switch that silences a whole family of diagnostics is the one that shows +/// them, exactly as an unreadable size cap leaves the cap on. +fn severity_switches(value: Option<&Value>) -> BTreeMap { + Severity::ALL + .into_iter() + .map(|severity| { + let on = flag(value.and_then(|v| v.get(severity.as_str()))).unwrap_or(true); + (severity, on) + }) + .collect() +} + +/// The rules a client said something explicit about: `on` and `off` only. +/// +/// `default` — and any word that is neither, and any key that is not a rule — +/// contributes nothing, which is what leaves the rule wherever the rest of the +/// ladder put it. See [`ClientSettings::lint_rules`]. +fn rule_toggles(value: Option<&Value>) -> BTreeMap { + let Some(Value::Object(map)) = value else { return BTreeMap::new() }; + map.iter() + .filter(|(name, _)| vlog_linter::rule_by_name(name).is_some()) + .filter_map(|(name, choice)| match choice.as_str() { + Some("on") => Some((name.clone(), true)), + Some("off") => Some((name.clone(), false)), + _ => None, + }) + .collect() } /// One of the two `lucisv.index.scope` words, or nothing. Matched exactly — @@ -623,6 +700,128 @@ mod tests { } } + /// **The drift guard.** `editors/vscode/package.json` declares one switch + /// per severity class and one per rule, generated by + /// `vlog_linter::vscode_lint_settings`. This compares the two as JSON + /// *values*, so formatting is free but a rule added without its toggle — + /// or a summary, default or severity edited on one side only — fails here. + /// + /// Regenerate with + /// `cargo run -p vlog_linter --example vscode_lint_settings`. + #[test] + fn the_vscode_lint_toggles_match_the_registry() { + 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"] + .as_object() + .expect("a properties object"); + let declared: serde_json::Map = properties + .iter() + .filter(|(key, _)| { + key.starts_with("lucisv.lint.severity.") || key.starts_with("lucisv.lint.rules.") + }) + .map(|(key, value)| (key.clone(), value.clone())) + .collect(); + + let generated: Value = serde_json::from_str(&vlog_linter::vscode_lint_settings()) + .expect("the generator emits valid json"); + let generated = generated.as_object().expect("an object"); + + let names = |map: &serde_json::Map| { + let mut keys: Vec = map.keys().cloned().collect(); + keys.sort(); + keys + }; + assert_eq!( + names(&declared), + names(generated), + "package.json and the rule registry disagree about which lint settings exist; \ + regenerate with `cargo run -p vlog_linter --example vscode_lint_settings`" + ); + for (key, value) in generated { + assert_eq!(declared.get(key), Some(value), "{key} drifted"); + } + // And every rule really does have one, which is the promise the whole + // generator exists to keep. + for rule in vlog_linter::all_rules() { + assert!(declared.contains_key(&vlog_linter::rule_setting(rule)), "{}", rule.name()); + } + } + + /// A default-everything payload — which is what a client sends for a user + /// who has touched nothing — must say nothing about any rule. + #[test] + fn the_shipped_lint_toggles_are_no_opinion() { + let mut rules = serde_json::Map::new(); + for rule in vlog_linter::all_rules() { + rules.insert(rule.name().to_string(), json!("default")); + } + let found = settings(json!({"lucisv": {"lint": { + "severity": {"error": true, "warning": true, "style": true}, + "rules": Value::Object(rules), + }}})); + assert_eq!(found, ClientSettings::default(), "every shipped value is silence"); + } + + #[test] + fn the_severity_switches_and_rule_toggles_are_read() { + let found = settings(json!({"lucisv": {"lint": { + "severity": {"style": false, "warning": "yes"}, + "rules": {"no-tabs": "on", "unused-signal": "off", "empty-item": "default", + "no-such-rule": "on", "case-missing-default": 3}, + }}})); + assert!(!found.lint_severity[&Severity::Style]); + assert!(found.lint_severity[&Severity::Warning], "a wrong type leaves it on"); + assert!(found.lint_severity[&Severity::Error], "and so does absence"); + assert_eq!( + found.lint_rules, + [("no-tabs".to_string(), true), ("unused-signal".to_string(), false)] + .into_iter() + .collect::>(), + "`default`, an unknown rule and a wrong-typed choice all say nothing" + ); + // A `lint` that is not an object leaves every class on and nothing said. + let junk = settings(json!({"lucisv": {"lint": 7}})); + assert_eq!(junk.lint_severity, every_class_on()); + assert!(junk.lint_rules.is_empty()); + } + + /// A severity word is a legal `select`/`ignore` entry since §33.0, so the + /// validating filter must keep it. + #[test] + fn a_severity_word_survives_the_select_and_ignore_filter() { + let found = settings(json!({"lucisv": {"lint": { + "select": ["style", "no-tabs", "nope"], + "ignore": ["warning"], + }}})); + assert_eq!(found.lint_select, vec!["style", "no-tabs"]); + assert_eq!(found.lint_ignore, vec!["warning"]); + } + + /// What the server compares two settings pushes by, to decide whether the + /// squiggles it already drew are still right. + #[test] + fn the_lint_selection_notices_every_setting_that_changes_the_rule_set() { + let base = ClientSettings::default(); + let mut severity = base.clone(); + severity.lint_severity.insert(Severity::Style, false); + let mut toggled = base.clone(); + toggled.lint_rules.insert("no-tabs".to_string(), false); + let mut selected = base.clone(); + selected.lint_select = vec!["error".to_string()]; + let mut ignored = base.clone(); + ignored.lint_ignore = vec!["no-tabs".to_string()]; + for changed in [severity, toggled, selected, ignored] { + assert_ne!(lint_selection(&base), lint_selection(&changed)); + } + // A setting that does not change which rules run does not republish. + let mut unrelated = base.clone(); + unrelated.indent = Some(4); + assert_eq!(lint_selection(&base), lint_selection(&unrelated)); + } + #[test] fn the_default_vscode_payload_is_no_opinion_about_anything() { // Every setting at its `package.json` default: nulls and an empty diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 82d833c..531d319 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -455,7 +455,9 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() { assert!(codes.contains(&"no-tabs"), "{codes:?}"); assert!(codes.contains(&"no-trailing-whitespace"), "{codes:?}"); for diagnostic in diagnostics { - assert_eq!(diagnostic["severity"], 2, "a lint finding is a warning"); + // Both rules here are style-class, which is LSP severity 3 + // (INFORMATION) since §33.0. + assert_eq!(diagnostic["severity"], 3, "a style finding is information"); assert_eq!(diagnostic["source"], "lucisv"); } diff --git a/crates/vlog_linter/examples/vscode_lint_settings.rs b/crates/vlog_linter/examples/vscode_lint_settings.rs new file mode 100644 index 0000000..037014c --- /dev/null +++ b/crates/vlog_linter/examples/vscode_lint_settings.rs @@ -0,0 +1,16 @@ +//! Prints the `lucisv.lint.severity.*` and `lucisv.lint.rules.*` settings for +//! `editors/vscode/package.json`, generated from the rule registry. +//! +//! ```text +//! cargo run -p vlog_linter --example vscode_lint_settings +//! ``` +//! +//! Paste the body of the printed object into that file's +//! `contributes.configuration.properties`, replacing the block that is there. +//! The drift test in `lucisv_server` (`settings::tests:: +//! the_vscode_lint_toggles_match_the_registry`) fails whenever the two +//! disagree, so a rule cannot ship without its toggle. + +fn main() { + print!("{}", vlog_linter::vscode_lint_settings()); +} diff --git a/crates/vlog_linter/src/context.rs b/crates/vlog_linter/src/context.rs index 242ee0d..d3be688 100644 --- a/crates/vlog_linter/src/context.rs +++ b/crates/vlog_linter/src/context.rs @@ -84,6 +84,16 @@ impl ParsedSource { &self.tokens } + /// The tolerant parse itself — public for the same reason [`tokens`] is: + /// a caller that has already paid for the parse can read the tree for + /// something else (`lucisv check` harvests its interface census off it) + /// instead of parsing the same text twice. + /// + /// [`tokens`]: ParsedSource::tokens + pub fn file(&self) -> &SourceFile { + &self.file + } + /// A lint context borrowing this parse. `path` is the file the text came /// from, or `None` for a buffer (stdin) — rules that need a filename skip. pub fn context(&self, path: Option) -> LintContext<'_> { @@ -125,6 +135,42 @@ enum Backing<'a> { pub trait MentionOracle: Sync { /// Whether any file **other than** the one being linted mentions `name`. fn mentioned_elsewhere(&self, name: &str) -> bool; + + /// What the project says the module or interface `name` declares, or + /// `None` when it cannot say — the unit is not in the project, or it is + /// declared more than once and the declarations disagree. + /// + /// The second question a rule may ask about other files, added by TODO + /// §33.2 for `unknown-port` and `unknown-parameter`. It is deliberately + /// still a *closed* question — the names a connection list may use, and + /// nothing about them — and `None` is a first-class answer that every + /// caller must treat as silence rather than as an empty list. A front end + /// with no such table at all answers `None` to everything, which leaves + /// those two rules quiet and every other rule exactly where it was. + fn module_interface(&self, _name: &str) -> Option { + None + } +} + +/// The names a module or interface declares that an instantiation may write. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ModuleInterface { + /// Port names, as written. + pub ports: Vec, + /// Overridable parameter names, as written — a `localparam` is not one. + pub parameters: Vec, +} + +impl ModuleInterface { + /// Whether the unit declares a port called `name`. + pub fn has_port(&self, name: &str) -> bool { + self.ports.iter().any(|port| port == name) + } + + /// Whether the unit declares an overridable parameter called `name`. + pub fn has_parameter(&self, name: &str) -> bool { + self.parameters.iter().any(|parameter| parameter == name) + } } /// Where a context's symbol table comes from: lent by a caller that already @@ -134,6 +180,12 @@ pub trait MentionOracle: Sync { /// Lazy rather than eager because most rules are syntactic: a run with no /// semantic rule enabled — which is every default `lucisv check`, since all /// three semantic rules ship off — must not pay for an analysis nobody reads. +// The `Lazy` variant is the table itself, held inline on purpose: it is one +// per lint run, it is written exactly once, and boxing it would add an +// allocation to the path that already avoided one by not analyzing at all. +// `Semantics` grew past clippy's variant-size threshold when it gained its +// `duplicates` table (§33.2); nothing about the trade changed with it. +#[allow(clippy::large_enum_variant)] enum SemanticsSlot<'a> { Lent(&'a Semantics), Lazy(OnceCell), @@ -156,6 +208,9 @@ pub struct LintContext<'a> { /// The signal table the semantic rules read, built once for all of them /// the first time one asks — and never for a run with none enabled. signals: OnceCell, + /// Whether the tolerant parse produced no `Error` leaf, answered once for + /// the rules that read structure. See [`LintContext::parsed_cleanly`]. + clean: OnceCell, /// What the workspace says about a name, when the caller has a workspace. /// `None` is a run that cannot see other files — a single-file /// `lucisv check`, stdin, a unit test — and every rule that would consult @@ -202,6 +257,7 @@ impl<'a> LintContext<'a> { strings: Vec::new(), semantics: SemanticsSlot::Lazy(OnceCell::new()), signals: OnceCell::new(), + clean: OnceCell::new(), oracle: None, }; ctx.strings = @@ -245,6 +301,13 @@ impl<'a> LintContext<'a> { self.oracle.is_some_and(|oracle| oracle.mentioned_elsewhere(name)) } + /// What the project says the unit `name` declares. `None` — no oracle, no + /// such unit, or two that disagree — means the run cannot answer, and a + /// rule that asked must then say nothing. + pub fn module_interface(&self, name: &str) -> Option { + self.oracle?.module_interface(name) + } + /// Whether this run can see other files at all. pub fn has_oracle(&self) -> bool { self.oracle.is_some() @@ -266,6 +329,32 @@ impl<'a> LintContext<'a> { self.signals.get_or_init(|| Signals::scan(self)) } + /// Whether the whole file fit the grammar — no `Error` leaf anywhere in + /// the tolerant parse. + /// + /// The tolerant parse is what makes a text rule work in a half-written + /// buffer, and most rules are right to ignore the difference. A rule that + /// reads **structure** is not: error recovery unwinds out of the construct + /// it failed in, so the declarations that followed are bound in whatever + /// scope recovery landed in — a class method's locals end up at file + /// scope, and every one of them looks like a redeclaration of the last + /// method's. Measured on opentitan: `spi_device_scoreboard.sv` (454 parse + /// errors, a macro-heavy UVM file) produced sixteen such phantoms, which + /// is sixteen wrong accusations from one file. A rule that would rather be + /// silent than wrong asks this first. + pub fn parsed_cleanly(&self) -> bool { + *self.clean.get_or_init(|| { + let mut clean = true; + crate::visit::walk_items(self.file(), &mut |item| { + clean &= !matches!(item.kind, vlog_parser::ast::ItemKind::Error(_)); + }); + crate::visit::walk_all_stmts(self.file(), &mut |stmt| { + clean &= !matches!(stmt.kind, vlog_parser::ast::StmtKind::Error(_)); + }); + clean + }) + } + /// The source text being linted. pub fn source(&self) -> &str { match &self.backing { diff --git a/crates/vlog_linter/src/decls.rs b/crates/vlog_linter/src/decls.rs new file mode 100644 index 0000000..564b716 --- /dev/null +++ b/crates/vlog_linter/src/decls.rs @@ -0,0 +1,229 @@ +//! Every declared type and every dimension in a file. +//! +//! A `DataType` is written in a dozen places — a port, a parameter, a +//! declarator, a typedef's base, a struct member, a subroutine's return type +//! and its arguments — and the rules that judge a *type* (the packed-dimension +//! ordering, a negative array bound) care about all of them equally. Collecting +//! them lives here rather than in `visit`, which is about the item and +//! statement spines; keeping the two apart is what stops either file from +//! becoming "everything a rule might want to walk". + +use vlog_parser::ast::{ + DataType, Dim, EnumType, FunctionDecl, ItemKind, SourceFile, StmtKind, StructType, TaskDecl, + TfArg, TypeExtra, TypedefKind, +}; + +use crate::visit::{walk_all_stmts, walk_items, walk_param_ports}; + +/// Where a dimension was written. The two are different constructs with +/// different conventions — `[N-1:0]` for a packed vector, `[N]` for an array — +/// so a rule that judges one must not judge the other by accident. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Packing { + /// Written before the declared name: a vector's width. + Packed, + /// Written after it: an array's extent. + Unpacked, +} + +/// Calls `f` on every data type written in the file, an anonymous aggregate's +/// members and base included. +pub(crate) fn walk_data_types(file: &SourceFile, f: &mut dyn FnMut(&DataType)) { + let mut visit = |ty: &DataType| descend(ty, f); + walk_param_ports(file, &mut |port| visit(&port.ty)); + walk_items(file, &mut |item| match &item.kind { + ItemKind::Module(module) => { + if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports { + for port in ports { + visit(&port.ty); + } + } + } + ItemKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit), + ItemKind::ParamDecl(decl) => visit(&decl.ty), + ItemKind::DataDecl(decl) => visit(&decl.ty), + ItemKind::PortDecl(decl) => visit(&decl.ty), + ItemKind::Function(decl) => function_types(decl, &mut visit), + ItemKind::Task(decl) => task_types(decl, &mut visit), + _ => {} + }); + walk_all_stmts(file, &mut |stmt| match &stmt.kind { + StmtKind::VarDecl(decl) => visit(&decl.ty), + StmtKind::ParamDecl(decl) => visit(&decl.ty), + StmtKind::PortDecl(decl) => visit(&decl.ty), + StmtKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit), + _ => {} + }); +} + +/// Calls `f` on every dimension in the file, saying which kind it is. +pub(crate) fn walk_dims(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) { + walk_data_types(file, &mut |ty| { + for dim in &ty.packed { + f(Packing::Packed, dim); + } + }); + walk_unpacked(file, f); +} + +/// The unpacked half: the `[…]` written *after* a declared name. +fn walk_unpacked(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) { + let mut unpacked = |dims: &[Dim]| { + for dim in dims { + f(Packing::Unpacked, dim); + } + }; + walk_param_ports(file, &mut |port| unpacked(&port.unpacked)); + walk_items(file, &mut |item| match &item.kind { + ItemKind::Module(module) => { + if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports { + for port in ports { + unpacked(&port.unpacked); + } + } + } + ItemKind::Typedef(typedef) => unpacked(&typedef.unpacked), + ItemKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked), + ItemKind::DataDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked), + ItemKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked), + ItemKind::Function(decl) => arg_dims(&decl.args, &mut unpacked), + ItemKind::Task(decl) => arg_dims(&decl.args, &mut unpacked), + _ => {} + }); + walk_all_stmts(file, &mut |stmt| match &stmt.kind { + StmtKind::VarDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked), + StmtKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked), + StmtKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked), + StmtKind::Typedef(typedef) => unpacked(&typedef.unpacked), + _ => {} + }); +} + +fn declarator_dims(declarators: &[vlog_parser::ast::Declarator], unpacked: &mut dyn FnMut(&[Dim])) { + for declarator in declarators { + unpacked(&declarator.unpacked); + } +} + +fn arg_dims(args: &[TfArg], unpacked: &mut dyn FnMut(&[Dim])) { + for arg in args { + unpacked(&arg.unpacked); + } +} + +fn typedef_types(kind: &TypedefKind, visit: &mut dyn FnMut(&DataType)) { + match kind { + TypedefKind::Alias(ty) => visit(ty), + TypedefKind::Enum(enum_ty) => enum_types(enum_ty, visit), + TypedefKind::Struct(struct_ty) => struct_types(struct_ty, visit), + TypedefKind::ForwardClass => {} + } +} + +fn function_types(decl: &FunctionDecl, visit: &mut dyn FnMut(&DataType)) { + if let Some(ret) = &decl.ret { + visit(ret); + } + for arg in &decl.args { + visit(&arg.ty); + } +} + +fn task_types(decl: &TaskDecl, visit: &mut dyn FnMut(&DataType)) { + for arg in &decl.args { + visit(&arg.ty); + } +} + +fn enum_types(enum_ty: &EnumType, visit: &mut dyn FnMut(&DataType)) { + if let Some(base) = &enum_ty.base { + visit(base); + } +} + +fn struct_types(struct_ty: &StructType, visit: &mut dyn FnMut(&DataType)) { + for member in &struct_ty.members { + visit(&member.ty); + } +} + +/// One type and whatever aggregate it *is*: an anonymous `enum`'s base and an +/// anonymous `struct`'s members are types written inside this one. +fn descend(ty: &DataType, f: &mut dyn FnMut(&DataType)) { + f(ty); + match ty.inline() { + Some(TypeExtra::Enum(enum_ty)) => enum_types(enum_ty, &mut |inner| descend(inner, f)), + Some(TypeExtra::Struct(struct_ty)) => { + struct_types(struct_ty, &mut |inner| descend(inner, f)) + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vlog_parser::parse_source_tolerant; + + fn packed_widths(src: &str) -> Vec { + let (file, _) = parse_source_tolerant(src); + let mut out = Vec::new(); + walk_dims(&file, &mut |packing, dim| { + if packing == Packing::Packed { + out.push(src[dim.span.as_range()].to_string()); + } + }); + out + } + + fn unpacked_extents(src: &str) -> Vec { + let (file, _) = parse_source_tolerant(src); + let mut out = Vec::new(); + walk_dims(&file, &mut |packing, dim| { + if packing == Packing::Unpacked { + out.push(src[dim.span.as_range()].to_string()); + } + }); + out + } + + #[test] + fn reaches_the_packed_dimensions_of_every_declaration_shape() { + let src = "module m #(parameter logic [1:0] P = 0) (\n\ + input logic [2:0] a\n\ + );\n\ + logic [3:0] b;\n\ + typedef logic [4:0] w_t;\n\ + function logic [5:0] f(input logic [6:0] x);\n\ + logic [7:0] local_v;\n\ + return 0;\n\ + endfunction\n\ + endmodule\n"; + assert_eq!( + packed_widths(src), + vec!["[1:0]", "[2:0]", "[3:0]", "[4:0]", "[5:0]", "[6:0]", "[7:0]"] + ); + } + + #[test] + fn reaches_an_anonymous_aggregates_members_and_base() { + let src = "module m;\n\ + struct packed { logic [1:0] a; logic [2:0] b; } s;\n\ + enum logic [3:0] { A } e;\n\ + endmodule\n"; + assert_eq!(packed_widths(src), vec!["[1:0]", "[2:0]", "[3:0]"]); + } + + #[test] + fn packed_and_unpacked_are_told_apart() { + let src = "module m;\n logic [1:0] q [4];\nendmodule\n"; + assert_eq!(packed_widths(src), vec!["[1:0]"]); + assert_eq!(unpacked_extents(src), vec!["[4]"]); + } + + #[test] + fn a_struct_member_is_reached_through_a_typedef() { + let src = "typedef struct packed {\n logic [9:0] wide;\n} w_t;\n"; + assert_eq!(packed_widths(src), vec!["[9:0]"]); + } +} diff --git a/crates/vlog_linter/src/interfaces.rs b/crates/vlog_linter/src/interfaces.rs new file mode 100644 index 0000000..f33eee1 --- /dev/null +++ b/crates/vlog_linter/src/interfaces.rs @@ -0,0 +1,178 @@ +//! What each module in one file declares that an instantiation may name. +//! +//! The language server answers [`MentionOracle::module_interface`] from its +//! workspace index, which already records every module's ports and parameters. +//! `lucisv check` has no index, so it reads the same facts off the parse it +//! makes anyway — this file is that reading, and it lives here so the CLI and +//! the linter cannot come to disagree about what "a port of this module" is. +//! +//! Erring is one-directional on purpose: a unit whose header lucisv cannot see +//! whole is reported as **unknowable** rather than as a short list, because a +//! short list is what turns a legal connection into an accusation. + +use vlog_parser::ast::{ItemKind, Module, ParamPort, PortList, SourceFile}; + +use crate::context::ModuleInterface; +use crate::visit::walk_items; + +/// Every module, interface and program the file declares, with what it +/// exposes. `None` for a unit whose header cannot be read whole. +/// +/// A file may declare a name twice (two `` `ifdef`` arms, a copy-paste); the +/// caller merges across files and must treat any disagreement as unknowable, +/// so both entries are returned rather than one. +pub fn module_interfaces(file: &SourceFile) -> Vec<(String, Option)> { + let mut out = Vec::new(); + walk_items(file, &mut |item| { + if let ItemKind::Module(module) = &item.kind { + out.push((module.name.clone(), interface_of(module))); + } + }); + out +} + +/// One unit's surface, or `None` when its header is not fully visible. +fn interface_of(module: &Module) -> Option { + // A directive written *between* ports or parameters may be a conditional + // — whose arms are all in the list, so the list stays a superset — or a + // macro invocation standing where a port belongs, whose expansion lucisv + // never sees. Telling the two apart would be a second preprocessor; a + // header with any directive in it is simply not answered for. + if !module.port_directives.is_empty() || !module.param_directives.is_empty() { + return None; + } + Some(ModuleInterface { ports: ports_of(module), parameters: parameters_of(module) }) +} + +/// The port names of either header style. A header with no port list at all +/// declares none, which is a fact rather than a gap: nothing may be connected +/// to it by name. +fn ports_of(module: &Module) -> Vec { + match &module.ports { + PortList::Ansi(ports) => ports.iter().map(|port| port.name.clone()).collect(), + PortList::NonAnsi(ports) => ports.iter().map(|port| port.name.clone()).collect(), + PortList::None | PortList::Empty => Vec::new(), + } +} + +/// The names an `#(.NAME(value))` override may write: every `parameter` in the +/// header and in the body. +/// +/// A `localparam` is **not** one — it is the module's own constant and is not +/// overridable (IEEE 1800 §6.20.4), which is exactly the distinction +/// `SymbolKind::LocalParam` was parted out for. A header parameter written +/// without a keyword continues the previous declaration and inherits its +/// keyword, which is how `#(parameter int A = 1, B = 2)` declares two +/// overridable parameters. +fn parameters_of(module: &Module) -> Vec { + let mut out = Vec::new(); + let mut overridable = true; + for port in module.param_ports.iter().flatten() { + overridable = is_parameter(port, overridable); + if overridable { + out.push(port.name.clone()); + } + } + for item in &module.items { + if let ItemKind::ParamDecl(decl) = &item.kind { + if decl.kw == "parameter" { + out.extend(decl.declarators.iter().map(|d| d.name.clone())); + } + } + } + out +} + +/// Whether this header parameter is overridable, given whether the one before +/// it was: a written keyword decides, and no keyword continues. +fn is_parameter(port: &ParamPort, previous: bool) -> bool { + match port.kw.as_deref() { + Some("localparam") => false, + Some(_) => true, + None => previous, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vlog_parser::parse_source_tolerant; + + fn interfaces(src: &str) -> Vec<(String, Option)> { + let (file, _) = parse_source_tolerant(src); + module_interfaces(&file) + } + + fn only(src: &str) -> ModuleInterface { + let found = interfaces(src); + assert_eq!(found.len(), 1, "{found:?}"); + found.into_iter().next().and_then(|(_, i)| i).expect("a readable header") + } + + #[test] + fn reads_an_ansi_header() { + let read = only( + "module m #(parameter int Width = 8, localparam int Derived = Width + 1) (\n\ + input logic clk_i,\n\ + output logic [7:0] data_o\n\ + );\n\ + endmodule\n", + ); + assert_eq!(read.ports, vec!["clk_i", "data_o"]); + assert_eq!(read.parameters, vec!["Width"], "a localparam is not overridable"); + } + + #[test] + fn reads_a_non_ansi_header() { + let read = only("module m (clk, rst_n);\n input clk;\n input rst_n;\nendmodule\n"); + assert_eq!(read.ports, vec!["clk", "rst_n"]); + } + + #[test] + fn a_continuation_parameter_inherits_its_keyword() { + let read = only("module m #(parameter int A = 1, B = 2) ();\nendmodule\n"); + assert_eq!(read.parameters, vec!["A", "B"]); + let local = only("module m #(localparam int A = 1, B = 2) ();\nendmodule\n"); + assert!(local.parameters.is_empty(), "both continue the localparam"); + } + + #[test] + fn a_body_parameter_is_overridable_and_a_body_localparam_is_not() { + let read = + only("module m ();\n parameter int Depth = 4;\n localparam int W = 2;\nendmodule\n"); + assert_eq!(read.parameters, vec!["Depth"]); + } + + #[test] + fn a_header_with_a_directive_in_it_is_unknowable() { + let src = "module m (\n\ + `ifdef X\n\ + input logic a,\n\ + `endif\n\ + input logic b\n\ + );\n\ + endmodule\n"; + assert_eq!(interfaces(src), vec![("m".to_string(), None)]); + } + + #[test] + fn a_port_less_module_declares_no_ports() { + let read = only("module m;\nendmodule\n"); + assert!(read.ports.is_empty()); + assert!(read.parameters.is_empty()); + let empty = only("module m ();\nendmodule\n"); + assert!(empty.ports.is_empty()); + } + + #[test] + fn an_interface_is_read_the_same_way() { + let read = only("interface bus_if (input logic clk);\nendinterface\n"); + assert_eq!(read.ports, vec!["clk"]); + } + + #[test] + fn every_unit_of_a_file_is_returned() { + let found = interfaces("module a ();\nendmodule\nmodule b ();\nendmodule\n"); + assert_eq!(found.iter().map(|(name, _)| name.as_str()).collect::>(), vec!["a", "b"]); + } +} diff --git a/crates/vlog_linter/src/lib.rs b/crates/vlog_linter/src/lib.rs index 2240f5a..a2218af 100644 --- a/crates/vlog_linter/src/lib.rs +++ b/crates/vlog_linter/src/lib.rs @@ -21,26 +21,36 @@ //! `docs/features/linter-core/README.md`. mod context; +mod decls; +mod interfaces; +mod literal; mod naming; mod registry; mod rule_docs; mod rules; +mod severity; mod signals; mod violation; mod visit; +mod vscode; mod waiver; use std::path::PathBuf; -pub use context::{LintContext, MentionOracle, ParsedSource}; -pub use registry::{all_rules, default_rules, rule_by_name, select_rules, workspace_rules, Rule}; +pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource}; +pub use interfaces::module_interfaces; +pub use registry::{ + all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule, +}; pub use rule_docs::rules_markdown; +pub use severity::Severity; pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation}; /// The identifier census a [`MentionOracle`] is answered from, re-exported /// from `vlog_semantic` so a front end that implements the oracle needs this /// crate alone. One harvest for the whole workspace — see /// `docs/features/semantic-lints-on/README.md`. pub use vlog_semantic::words; +pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES}; pub use waiver::UNUSED_WAIVER; use waiver::Waivers; @@ -87,9 +97,24 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec kept.sort_by(|a, b| { (a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule)) }); + stamp_severities(&mut kept); kept } +/// Gives every finding the class its rule declares. +/// +/// One place rather than one per rule: a rule's `check` builds violations +/// without knowing what it is called, the `unused-waiver` findings are built by +/// the waiver scanner and not by a rule at all, and a severity written twice +/// would eventually be written differently. See [`Violation::severity`]. +fn stamp_severities(violations: &mut [Violation]) { + for violation in violations { + if let Some(rule) = rule_by_name(violation.rule) { + violation.severity = rule.severity(); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -211,6 +236,27 @@ mod tests { assert!(run(src, None, &enabled).is_empty()); } + /// Every finding the runner returns carries its rule's class — including + /// the `unused-waiver` ones, which no rule's `check` produced. + #[test] + fn the_runner_stamps_every_finding_with_its_rules_severity() { + let src = "module m;\n\ + \treg a; // lucisv: waive no-such-rule\n\ + \talways_comb a <= 1'b0;\n\ + endmodule\n"; + let found = run(src, Some(PathBuf::from("rtl/m.sv")), &default_rules()); + assert!(found.len() >= 3, "{found:#?}"); + for violation in &found { + let rule = rule_by_name(violation.rule).expect("a registered rule"); + assert_eq!(violation.severity, rule.severity(), "{}", violation.rule); + } + let by_rule = + |name: &str| found.iter().find(|v| v.rule == name).map(|v| v.severity).expect(name); + assert_eq!(by_rule("wire-reg-mixup"), Severity::Error); + assert_eq!(by_rule("always-comb-blocking"), Severity::Warning); + assert_eq!(by_rule(UNUSED_WAIVER), Severity::Style); + } + #[test] fn a_file_that_does_not_parse_still_gets_its_text_rules() { let src = "module m;\n\t@@@ this is not verilog\nendmodule\n"; diff --git a/crates/vlog_linter/src/literal.rs b/crates/vlog_linter/src/literal.rs new file mode 100644 index 0000000..e90d17b --- /dev/null +++ b/crates/vlog_linter/src/literal.rs @@ -0,0 +1,156 @@ +//! Sized based literals, read the way the two width rules need them. +//! +//! `truncated-numeric-literal` asks "how many bits does what is written +//! actually need?" and `undersized-binary-literal` asks "how many digits were +//! written?". Both questions are about the same `'` shape, +//! so it is parsed once here rather than twice, slightly differently. + +/// One `'[s]` literal, as written. +/// +/// Only the *sized* spelling is modelled: an unsized `'h1f` takes its width +/// from context, so neither rule has anything to compare against and +/// [`parse`] returns `None` for it. +pub(crate) struct SizedLiteral<'a> { + /// The declared width, in bits. + pub width: u32, + /// The base letter, lower-cased: `b`, `o`, `d` or `h`. + pub base: char, + /// The digits as written, `_` separators included. + pub digits: &'a str, +} + +impl SizedLiteral<'_> { + /// The digits with the `_` separators taken out. + pub fn packed_digits(&self) -> String { + self.digits.chars().filter(|c| *c != '_').collect() + } + + /// How many bits the written value really needs, or `None` when that + /// cannot be said: an empty or malformed digit run, or a decimal value + /// carrying `x`/`z`. + /// + /// A digit that is `x`, `z` or `?` counts as full-width — `4'hxF` needs + /// eight bits, because the unknown nibble is still a nibble. + pub fn significant_bits(&self) -> Option { + let digits = self.packed_digits(); + let digits = digits.trim_start_matches('0'); + if digits.is_empty() { + return Some(0); + } + let Some(per_digit) = bits_per_digit(self.base) else { + // Decimal: the whole run is one number, so an `x` in it makes the + // value unknown rather than one unknown digit. + let value: u128 = digits.parse().ok()?; + return Some(128 - value.leading_zeros()); + }; + let mut chars = digits.chars(); + let first = chars.next()?; + let rest = chars.count() as u32; + let head = match first.to_ascii_lowercase() { + 'x' | 'z' | '?' => per_digit, + c => bits_of(c, self.base)?, + }; + Some(rest * per_digit + head) + } +} + +/// Reads a sized based literal, or `None` for anything else — an unsized +/// literal, a plain decimal, a real, a time literal. +pub(crate) fn parse(text: &str) -> Option> { + let (size, rest) = text.split_once('\'')?; + let width: u32 = size.chars().filter(|c| *c != '_').collect::().parse().ok()?; + // `8'sh1f` — the signedness marker sits between the tick and the base. + let rest = rest.strip_prefix(['s', 'S']).unwrap_or(rest); + let mut chars = rest.chars(); + let base = chars.next()?.to_ascii_lowercase(); + if !matches!(base, 'b' | 'o' | 'd' | 'h') { + return None; + } + let digits = rest.get(1..)?; + if digits.is_empty() || !digits.chars().all(|c| is_digit_of(c, base) || c == '_') { + return None; + } + Some(SizedLiteral { width, base, digits }) +} + +/// How many bits one digit of `base` carries; `None` for decimal, which is not +/// a per-digit base at all. +fn bits_per_digit(base: char) -> Option { + match base { + 'b' => Some(1), + 'o' => Some(3), + 'h' => Some(4), + _ => None, + } +} + +/// How many bits one known digit's value needs (`7` needs three, `1` needs +/// one), or `None` when the character is not a digit of this base. +fn bits_of(c: char, base: char) -> Option { + let value = c.to_digit(16)?; + let per_digit = bits_per_digit(base)?; + if value >= 1 << per_digit { + return None; + } + Some(32 - value.leading_zeros()) +} + +/// True when `c` may stand among `base`'s digits, unknowns included. +fn is_digit_of(c: char, base: char) -> bool { + let c = c.to_ascii_lowercase(); + if matches!(c, 'x' | 'z' | '?') { + return true; + } + match base { + 'b' => matches!(c, '0' | '1'), + 'o' => c.is_digit(8), + 'd' => c.is_ascii_digit(), + _ => c.is_ascii_hexdigit(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bits(text: &str) -> Option { + parse(text)?.significant_bits() + } + + #[test] + fn a_sized_literal_is_read_in_every_base() { + for (text, width, base, digits) in [ + ("8'hFF", 8, 'h', "FF"), + ("4'b1010", 4, 'b', "1010"), + ("3'o7", 3, 'o', "7"), + ("16'd1000", 16, 'd', "1000"), + ("8'sh1f", 8, 'h', "1f"), + ("32'hdead_beef", 32, 'h', "dead_beef"), + ] { + let found = parse(text).unwrap_or_else(|| panic!("{text}")); + assert_eq!((found.width, found.base, found.digits), (width, base, digits), "{text}"); + } + } + + #[test] + fn anything_that_is_not_a_sized_based_literal_is_declined() { + for text in ["'h1f", "42", "1.5", "10ns", "8'", "8'q1", "8'h", "8'hG", "'0"] { + assert!(parse(text).is_none(), "{text}"); + } + } + + #[test] + fn significant_bits_counts_what_is_written() { + assert_eq!(bits("4'h0"), Some(0)); + assert_eq!(bits("4'h1"), Some(1)); + assert_eq!(bits("4'h8"), Some(4)); + assert_eq!(bits("4'hFFF"), Some(12), "three full nibbles"); + assert_eq!(bits("8'b0000_0001"), Some(1), "leading zeros do not count"); + assert_eq!(bits("4'o7"), Some(3)); + assert_eq!(bits("8'd255"), Some(8)); + assert_eq!(bits("8'd256"), Some(9)); + assert_eq!(bits("4'hx"), Some(4), "an unknown nibble is still a nibble"); + assert_eq!(bits("4'h0x"), Some(4), "and leading zeros still do not count"); + assert_eq!(bits("8'dx"), None, "a decimal unknown says nothing about width"); + } +} diff --git a/crates/vlog_linter/src/registry.rs b/crates/vlog_linter/src/registry.rs index 5588f9b..5cc15c3 100644 --- a/crates/vlog_linter/src/registry.rs +++ b/crates/vlog_linter/src/registry.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::rules; +use crate::severity::Severity; use crate::violation::{Applicability, Violation}; /// One lint rule. @@ -17,6 +18,14 @@ pub trait Rule: Sync { /// One line, imperative, no trailing period. fn summary(&self) -> &'static str; + /// How bad this rule's findings are. + /// + /// Deliberately without a default: a class is a claim about what a finding + /// means to the user, and a rule that inherited one silently would be + /// making that claim by accident. The reason for the class chosen belongs + /// in [`Rule::doc`]. + fn severity(&self) -> Severity; + /// Why the rule exists — the style-guide rationale, in prose. fn doc(&self) -> &'static str; @@ -60,19 +69,38 @@ pub fn all_rules() -> Vec<&'static dyn Rule> { &rules::always_comb_blocking::AlwaysCombBlocking, &rules::always_ff_non_blocking::AlwaysFfNonBlocking, &rules::case_missing_default::CaseMissingDefault, + &rules::duplicate_declaration::DuplicateDeclaration, &rules::empty_item::EmptyItem, &rules::enum_name_style::EnumNameStyle, + &rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType, &rules::explicit_parameter_storage_type::ExplicitParameterStorageType, + &rules::forbid_defparam::ForbidDefparam, + &rules::forbid_negative_array_dim::ForbidNegativeArrayDim, + &rules::incomplete_assignment::IncompleteAssignment, + &rules::instance_shadowing::InstanceShadowing, + &rules::invalid_system_task_function::InvalidSystemTaskFunction, + &rules::mismatched_labels::MismatchedLabels, &rules::module_filename::ModuleFilename, &rules::module_name_style::ModuleNameStyle, + &rules::module_parameter::ModuleParameter, + &rules::module_port::ModulePort, &rules::multiply_driven::MultiplyDriven, &rules::no_tabs::NoTabs, &rules::no_trailing_whitespace::NoTrailingWhitespace, + &rules::packed_dimensions_range_ordering::PackedDimensionsRangeOrdering, &rules::parameter_name_style::ParameterNameStyle, + &rules::plusarg_assignment::PlusargAssignment, &rules::struct_union_name_style::StructUnionNameStyle, + &rules::suspicious_semicolon::SuspiciousSemicolon, + &rules::truncated_numeric_literal::TruncatedNumericLiteral, + &rules::undeclared_identifier::UndeclaredIdentifier, + &rules::undersized_binary_literal::UndersizedBinaryLiteral, &rules::undriven_net::UndrivenNet, + &rules::unknown_parameter::UnknownParameter, + &rules::unknown_port::UnknownPort, &rules::unused_signal::UnusedSignal, &rules::unused_waiver::UnusedWaiver, + &rules::void_cast::VoidCast, &rules::wire_reg_mixup::WireRegMixup, ] } @@ -112,10 +140,25 @@ pub fn rule_by_name(name: &str) -> Option<&'static dyn Rule> { all_rules().into_iter().find(|rule| rule.name() == name) } +/// The rules one `--select` / `--ignore` name stands for. +/// +/// A rule name stands for itself; a **severity name** (`error`, `warning`, +/// `style`) stands for every rule of that class, so `--ignore style` is one +/// word for the whole family. `None` for a name that is neither, which is what +/// makes a typo a failed run rather than a silently empty selection. +pub fn rules_named(name: &str) -> Option> { + if let Some(rule) = rule_by_name(name) { + return Some(vec![rule]); + } + let severity = Severity::from_name(name)?; + Some(all_rules().into_iter().filter(|rule| rule.severity() == severity).collect()) +} + /// The rules a run should use: `select` replaces the default set (empty means -/// keep it), then `ignore` removes from whatever is left. An unknown name on -/// either list is an error rather than a silent no-op — a typo'd `--select` -/// that quietly ran everything would be worse than a failed run. +/// keep it), then `ignore` removes from whatever is left. Either list may name +/// a rule or a whole severity ([`rules_named`]). An unknown name on either +/// list is an error rather than a silent no-op — a typo'd `--select` that +/// quietly ran everything would be worse than a failed run. /// /// `workspace` only reaches [`default_rules`]: an explicit `select` names the /// rules it wants and gets them, oracle or no oracle, exactly as an explicit @@ -128,25 +171,27 @@ pub fn select_rules( let mut chosen = if select.is_empty() { enabled_rules(workspace) } else { - let mut chosen = Vec::new(); + let mut chosen: Vec<&'static dyn Rule> = Vec::new(); for name in select { - let rule = rule_by_name(name).ok_or_else(|| unknown(name))?; - if !chosen.iter().any(|r: &&'static dyn Rule| r.name() == rule.name()) { - chosen.push(rule); + for rule in rules_named(name).ok_or_else(|| unknown(name))? { + if !chosen.iter().any(|r| r.name() == rule.name()) { + chosen.push(rule); + } } } chosen }; for name in ignore { - rule_by_name(name).ok_or_else(|| unknown(name))?; - chosen.retain(|rule| rule.name() != name); + let dropped = rules_named(name).ok_or_else(|| unknown(name))?; + chosen.retain(|rule| !dropped.iter().any(|d| d.name() == rule.name())); } Ok(chosen) } fn unknown(name: &str) -> String { let known = all_rules().iter().map(|r| r.name()).collect::>().join(", "); - format!("unknown rule: {name} (known rules: {known})") + let severities = Severity::ALL.iter().map(|s| s.as_str()).collect::>().join(", "); + format!("unknown rule: {name} (severities: {severities}; known rules: {known})") } #[cfg(test)] @@ -211,7 +256,17 @@ mod tests { let project: Vec<&str> = workspace_rules().iter().map(|r| r.name()).collect(); let added: Vec<&str> = project.iter().copied().filter(|name| !alone.contains(name)).collect(); - assert_eq!(added, vec!["multiply-driven", "undriven-net", "unused-signal"]); + assert_eq!( + added, + vec![ + "multiply-driven", + "undeclared-identifier", + "undriven-net", + "unknown-parameter", + "unknown-port", + "unused-signal", + ] + ); assert!(alone.iter().all(|name| project.contains(name)), "a workspace never removes one"); for rule in all_rules() { assert_eq!(rule.needs_workspace(), added.contains(&rule.name()), "{}", rule.name()); @@ -283,6 +338,95 @@ mod tests { assert!(message.contains("no-tabs"), "the error must list what is known: {message}"); } + /// Every rule states a class, and no rule name collides with a class + /// name — otherwise `--select error` would mean two things. + #[test] + fn every_rule_has_a_severity_and_no_name_shadows_a_class() { + for rule in all_rules() { + assert!(Severity::ALL.contains(&rule.severity()), "{}", rule.name()); + assert!( + Severity::from_name(rule.name()).is_none(), + "{} shadows a severity word", + rule.name() + ); + } + } + + /// The assignments §33.0 wrote down for the seventeen rules that predate + /// severities. A rule moving class is a user-visible change, so it moves + /// here first. + #[test] + fn the_original_seventeen_keep_the_classes_they_were_given() { + let expected: &[(&str, Severity)] = &[ + ("multiply-driven", Severity::Error), + ("wire-reg-mixup", Severity::Error), + ("always-comb-blocking", Severity::Warning), + ("always-ff-non-blocking", Severity::Warning), + ("case-missing-default", Severity::Warning), + ("undriven-net", Severity::Warning), + ("unused-signal", Severity::Warning), + ("empty-item", Severity::Style), + ("enum-name-style", Severity::Style), + ("explicit-parameter-storage-type", Severity::Style), + ("module-filename", Severity::Style), + ("module-name-style", Severity::Style), + ("no-tabs", Severity::Style), + ("no-trailing-whitespace", Severity::Style), + ("parameter-name-style", Severity::Style), + ("struct-union-name-style", Severity::Style), + ("unused-waiver", Severity::Style), + ]; + for (name, severity) in expected { + let rule = rule_by_name(name).unwrap_or_else(|| panic!("{name} exists")); + assert_eq!(rule.severity(), *severity, "{name}"); + } + } + + #[test] + fn a_severity_name_stands_for_every_rule_of_that_class() { + for severity in Severity::ALL { + let named = rules_named(severity.as_str()).unwrap_or_default(); + let expected: Vec<&str> = all_rules() + .into_iter() + .filter(|rule| rule.severity() == severity) + .map(|rule| rule.name()) + .collect(); + assert_eq!(named.iter().map(|r| r.name()).collect::>(), expected); + assert!(!expected.is_empty(), "{severity:?} has no rules"); + } + assert!(rules_named("no-tabs").is_some_and(|rules| rules.len() == 1)); + assert!(rules_named("no-such-thing").is_none()); + } + + /// `--select style`, `--ignore warning`: the whole point of the words. + #[test] + fn select_and_ignore_accept_a_severity_wherever_a_rule_fits() { + let styled = select_rules(&["style".to_string()], &[], true).unwrap(); + assert!(styled.iter().all(|rule| rule.severity() == Severity::Style)); + assert!(styled.iter().any(|rule| rule.name() == "no-tabs")); + + let quiet = select_rules(&[], &["style".to_string()], true).unwrap(); + assert!(quiet.iter().all(|rule| rule.severity() != Severity::Style)); + assert!(quiet.iter().any(|rule| rule.name() == "unused-signal"), "warnings survive"); + + // A severity and a rule name mix on one list, and the same rule named + // twice is still selected once. + let mixed = + select_rules(&["style".to_string(), "no-tabs".to_string()], &[], false).unwrap(); + assert_eq!(mixed.iter().filter(|rule| rule.name() == "no-tabs").count(), 1); + + // Ignoring a class removes it from an explicit selection too. + let none = select_rules(&["no-tabs".to_string()], &["style".to_string()], false).unwrap(); + assert!(none.is_empty()); + } + + #[test] + fn the_unknown_name_error_names_the_severity_words_too() { + let message = select_rules(&["styles".to_string()], &[], false).err().unwrap_or_default(); + assert!(message.contains("style"), "{message}"); + assert!(message.contains("no-tabs"), "{message}"); + } + #[test] fn lookup_by_name_finds_every_rule_and_nothing_else() { for rule in all_rules() { diff --git a/crates/vlog_linter/src/rule_docs.rs b/crates/vlog_linter/src/rule_docs.rs index 5ec684f..541a0bd 100644 --- a/crates/vlog_linter/src/rule_docs.rs +++ b/crates/vlog_linter/src/rule_docs.rs @@ -7,6 +7,7 @@ //! this. use crate::registry::all_rules; +use crate::severity::Severity; /// The whole rule reference as one markdown document. pub fn rules_markdown() -> String { @@ -15,6 +16,12 @@ pub fn rules_markdown() -> String { out.push_str( "Generated from the rule registry by `vlog_linter::rules_markdown` — \ do not edit by hand.\n\n\ + Every rule is in one of three **severity** classes, and the class is \ + a word `--select` and `--ignore` accept wherever a rule name fits \ + (`--ignore style`, `--select error`). **error** is code that would \ + very likely fail to compile, elaborate or synthesize; **warning** is \ + code that compiles but very likely does not mean what it says; \ + **style** is code that is correct and reads badly.\n\n\ A rule marked **on** runs for a plain `lucisv check`; the others need \ `--select `. A rule marked **on (project)** runs by default \ only where lucisv can see the other files of the project — \ @@ -26,23 +33,32 @@ pub fn rules_markdown() -> String { `.\n\n", ); - out.push_str("| Rule | Default | Fix |\n|---|---|---|\n"); + out.push_str("| Rule | Severity | Default | Fix |\n|---|---|---|---|\n"); for rule in all_rules() { out.push_str(&format!( - "| [`{name}`](#{name}) | {default} | {fix} |\n", + "| [`{name}`](#{name}) | {severity} | {default} | {fix} |\n", name = rule.name(), + severity = rule.severity().as_str(), default = default_word(rule), fix = fix_word(rule), )); } out.push('\n'); - for rule in all_rules() { - out.push_str(&format!("## {}\n\n", rule.name())); - out.push_str(&format!("{}.\n\n", capitalize(rule.summary()))); - out.push_str(&format!("- Default: {}\n- Fix: {}\n\n", default_word(rule), fix_word(rule))); - out.push_str(rule.doc()); - out.push_str("\n\n"); + for severity in Severity::ALL { + out.push_str(&format!("# {} — {}\n\n", severity.as_str(), severity.describes())); + for rule in all_rules().into_iter().filter(|rule| rule.severity() == severity) { + out.push_str(&format!("## {}\n\n", rule.name())); + out.push_str(&format!("{}.\n\n", capitalize(rule.summary()))); + out.push_str(&format!( + "- Severity: {}\n- Default: {}\n- Fix: {}\n\n", + severity.as_str(), + default_word(rule), + fix_word(rule), + )); + out.push_str(rule.doc()); + out.push_str("\n\n"); + } } out } @@ -98,7 +114,7 @@ mod tests { fn the_index_lists_every_rule_once() { let markdown = rules_markdown(); for rule in all_rules() { - let row = format!("| [`{0}`](#{0}) |", rule.name()); + let row = format!("| [`{0}`](#{0}) | ", rule.name()); assert_eq!(markdown.matches(&row).count(), 1, "{}", rule.name()); } } @@ -106,27 +122,62 @@ mod tests { #[test] fn defaults_and_fixes_are_rendered_from_the_registry() { let markdown = rules_markdown(); - assert!(markdown.contains("| [`no-tabs`](#no-tabs) | **on** | safe |")); - assert!(markdown.contains("| [`module-name-style`](#module-name-style) | off | none |")); + assert!(markdown.contains("| [`no-tabs`](#no-tabs) | style | **on** | safe |")); + assert!( + markdown.contains("| [`module-name-style`](#module-name-style) | style | off | none |") + ); // The three semantic rules are fixless, and default on exactly where // there is a project to ask about a name — see // docs/features/semantic-lints-on/README.md. - for name in ["multiply-driven", "undriven-net", "unused-signal"] { + for (name, severity) in [ + ("multiply-driven", "error"), + ("undriven-net", "warning"), + ("unused-signal", "warning"), + ] { assert!( - markdown.contains(&format!("| [`{name}`](#{name}) | **on (project)** | none |")), + markdown.contains(&format!( + "| [`{name}`](#{name}) | {severity} | **on (project)** | none |" + )), "{name}" ); } assert_eq!(fix_word(&crate::rules::no_tabs::NoTabs), Applicability::Safe.as_str()); } + /// Every rule sits under the heading of its own class, and the three + /// headings are written worst-first. + #[test] + fn the_sections_are_grouped_by_severity() { + let markdown = rules_markdown(); + let heading = |severity: Severity| { + markdown + .find(&format!("\n# {} — ", severity.as_str())) + .unwrap_or_else(|| panic!("{severity:?} heading")) + }; + let (error, warning, style) = + (heading(Severity::Error), heading(Severity::Warning), heading(Severity::Style)); + assert!(error < warning && warning < style, "worst first"); + for rule in all_rules() { + let at = markdown + .find(&format!("\n## {}\n", rule.name())) + .unwrap_or_else(|| panic!("{}", rule.name())); + let own = heading(rule.severity()); + let next = [error, warning, style] + .into_iter() + .filter(|start| *start > own) + .min() + .unwrap_or(markdown.len()); + assert!(own < at && at < next, "{} is under the wrong heading", rule.name()); + } + } + #[test] fn the_document_shape_is_pinned() { // A golden test on the *shape*, not on the prose: the heading, the // generated-by note, the index table header, and the first per-rule // section, which together are what a reader (and any renderer) sees. let markdown = rules_markdown(); - let head: Vec<&str> = markdown.lines().take(8).collect(); + let head: Vec<&str> = markdown.lines().take(10).collect(); assert_eq!( head, vec![ @@ -135,6 +186,12 @@ mod tests { "Generated from the rule registry by `vlog_linter::rules_markdown` — do not edit \ by hand.", "", + "Every rule is in one of three **severity** classes, and the class is a word \ + `--select` and `--ignore` accept wherever a rule name fits (`--ignore style`, \ + `--select error`). **error** is code that would very likely fail to compile, \ + elaborate or synthesize; **warning** is code that compiles but very likely does \ + not mean what it says; **style** is code that is correct and reads badly.", + "", "A rule marked **on** runs for a plain `lucisv check`; the others need \ `--select `. A rule marked **on (project)** runs by default only where \ lucisv can see the other files of the project — `lucisv check `, or the \ @@ -143,13 +200,16 @@ mod tests { rule can be turned off with `--ignore `, with `ignore` under `[lint]` in \ `lucisv.toml`, or waived in the source with `// lucisv: waive `.", "", - "| Rule | Default | Fix |", - "|---|---|---|", + "| Rule | Severity | Default | Fix |", + "|---|---|---|---|", ] ); - let first_rule = all_rules()[0]; + let first_rule = all_rules() + .into_iter() + .find(|rule| rule.severity() == Severity::Error) + .expect("some rule is an error"); let section = format!( - "## {}\n\n{}.\n\n- Default: {}\n- Fix: {}\n\n{}\n\n", + "## {}\n\n{}.\n\n- Severity: error\n- Default: {}\n- Fix: {}\n\n{}\n\n", first_rule.name(), capitalize(first_rule.summary()), default_word(first_rule), diff --git a/crates/vlog_linter/src/rules/always_comb_blocking.rs b/crates/vlog_linter/src/rules/always_comb_blocking.rs index e87640e..4f04d86 100644 --- a/crates/vlog_linter/src/rules/always_comb_blocking.rs +++ b/crates/vlog_linter/src/rules/always_comb_blocking.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use crate::visit::{walk_items, walk_stmts}; use vlog_parser::ast::{ItemKind, StmtKind}; @@ -20,6 +21,10 @@ impl Rule for AlwaysCombBlocking { "assign with `=` inside always_comb" } + fn severity(&self) -> Severity { + Severity::Warning + } + fn doc(&self) -> &'static str { "A non-blocking assignment in a combinational block schedules its \ update for the end of the time step, so a value read later in the same \ diff --git a/crates/vlog_linter/src/rules/always_ff_non_blocking.rs b/crates/vlog_linter/src/rules/always_ff_non_blocking.rs index 6d815e1..2fd2709 100644 --- a/crates/vlog_linter/src/rules/always_ff_non_blocking.rs +++ b/crates/vlog_linter/src/rules/always_ff_non_blocking.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use crate::visit::{walk_items, walk_stmts}; use vlog_parser::ast::{ItemKind, StmtKind}; @@ -20,6 +21,10 @@ impl Rule for AlwaysFfNonBlocking { "assign with `<=` inside always_ff" } + fn severity(&self) -> Severity { + Severity::Warning + } + fn doc(&self) -> &'static str { "A blocking assignment in a clocked block updates immediately, so two \ flops written in one `always_ff` can see each other's new value in \ diff --git a/crates/vlog_linter/src/rules/case_missing_default.rs b/crates/vlog_linter/src/rules/case_missing_default.rs index fcd7b9a..22f6241 100644 --- a/crates/vlog_linter/src/rules/case_missing_default.rs +++ b/crates/vlog_linter/src/rules/case_missing_default.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use crate::visit::{walk_all_stmts, walk_items}; use vlog_parser::ast::{CaseItem, GenCaseItem, ItemKind, StmtKind}; @@ -21,6 +22,10 @@ impl Rule for CaseMissingDefault { "give every case statement a default branch" } + fn severity(&self) -> Severity { + Severity::Warning + } + fn doc(&self) -> &'static str { "A case statement with no `default` infers a latch in combinational \ logic and leaves the unlisted patterns unspecified in simulation — the \ diff --git a/crates/vlog_linter/src/rules/duplicate_declaration.rs b/crates/vlog_linter/src/rules/duplicate_declaration.rs new file mode 100644 index 0000000..b5b0389 --- /dev/null +++ b/crates/vlog_linter/src/rules/duplicate_declaration.rs @@ -0,0 +1,197 @@ +//! `duplicate-declaration` — one name declared twice in one scope. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_semantic::{ScopeKind, SymbolKind}; + +/// See [`Rule::doc`]. +pub struct DuplicateDeclaration; + +const NAME: &str = "duplicate-declaration"; + +impl Rule for DuplicateDeclaration { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "declare each name once per scope" + } + + fn severity(&self) -> Severity { + Severity::Error + } + + fn doc(&self) -> &'static str { + "Two declarations of one name in one scope is an elaboration error in \ + every tool (IEEE 1800 §3.13 — an identifier is unique within its \ + namespace and scope). It happens when a signal is copied and the \ + paste is not renamed, when two parameters are merged from different \ + branches, or when a `logic` is declared beside the `input` of the \ + same name. Verible has no equivalent rule; this is TODO §33's own, \ + and it is an **Error** because the file will not compile.\n\n\ + **Silent whenever the second declaration might be legal**, which is \ + the rule every Error-class check here follows. It says nothing when \ + either declaration is a **port** — a non-ANSI port is *completed* by \ + a body `input clk;` and then by a `logic clk;`, all three of which \ + are the same port and all three legal — nor about a function, task, \ + class, constraint, covergroup, property, sequence, modport or \ + clocking name, each of which has a legal prototype-plus-definition \ + or forward-declaration shape. It says nothing inside a `generate` \ + scope, where only one arm is ever elaborated, and nothing when a \ + conditional-compilation directive stands between the two \ + declarations, which is that same exclusivity written for the \ + preprocessor. What is left is two ordinary declarations of one name, \ + side by side, in one scope. No automatic fix: which of the two the \ + author meant to keep is not something a linter can know." + } + + fn check(&self, ctx: &LintContext) -> Vec { + // Error recovery rebinds whatever followed a construct it could not + // parse into whatever scope it unwound to, which turns every later + // local into a phantom redeclaration. An Error-class rule says nothing + // about a file it cannot trust the shape of. + if !ctx.parsed_cleanly() { + return Vec::new(); + } + let semantics = ctx.semantics(); + let mut out = Vec::new(); + for duplicate in semantics.duplicates() { + let Some(first) = semantics.symbol(duplicate.first) else { continue }; + if !plain(duplicate.kind) || !plain(first.kind) { + continue; + } + let scope = semantics.scope(duplicate.scope).map(|scope| scope.kind); + // A generate scope elaborates one arm at a time; the file scope is + // where a `` `include``d fragment and a recovered construct both + // land, and two file-scope units of one name are the workspace's + // business rather than this file's. + if matches!(scope, Some(ScopeKind::Generate) | Some(ScopeKind::File)) { + continue; + } + let spans = [first.name_span.start, duplicate.name_span.start]; + if ctx.signals().conditional_between(&spans) { + continue; + } + out.push(Violation::new( + NAME, + format!("`{}` is already declared in this scope", duplicate.name), + duplicate.name_span, + )); + } + out + } +} + +/// True for the declaration kinds that may be written **once** and once only. +/// +/// Everything left out has a legal shape in which the same name is written +/// twice: a port is completed by its body declaration, a function or task by +/// its out-of-body definition, a class by its `typedef class` forward +/// declaration, and a constraint, covergroup, property or sequence by its own +/// prototype. An **enum member** is left out for a different reason: IEEE 1800 +/// §6.19's name *range* (`RvCoreCsrGprT[0:2]`) declares a run of members under +/// one written identifier, and the binder records the identifier — so two +/// disjoint ranges of one base name look like one name declared twice when the +/// members they declare do not collide at all (measured on opentitan: +/// `jtag_rv_debugger_pkg.sv`). Listed positively rather than as an exclusion +/// list, so a kind added to `vlog_semantic` later is silent until somebody +/// decides it belongs. +fn plain(kind: SymbolKind) -> bool { + matches!( + kind, + SymbolKind::Net + | SymbolKind::Var + | SymbolKind::Param + | SymbolKind::LocalParam + | SymbolKind::Genvar + | SymbolKind::Typedef + | SymbolKind::Instance + | SymbolKind::TfArg + | SymbolKind::StructMember + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + DuplicateDeclaration.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_two_signals_of_one_name() { + let src = "module m;\n logic a;\n logic a;\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`a`"), "{}", found[0].message); + assert_eq!(found[0].span.start as usize, src.rfind('a').map(|i| i - 1).unwrap_or(0) + 1); + assert!(found[0].fix.is_none()); + } + + #[test] + fn flags_two_parameters_two_typedefs_and_two_instances() { + for src in [ + "module m;\n parameter int W = 1;\n parameter int W = 2;\nendmodule\n", + "module m;\n typedef logic t;\n typedef bit t;\nendmodule\n", + "module m;\n sub u ();\n sub u ();\nendmodule\n", + ] { + assert_eq!(violations(src).len(), 1, "{src}"); + } + } + + /// The non-ANSI shape: the header names the port, the body declares its + /// direction and then its type. Three declarations, one port, all legal. + #[test] + fn a_non_ansi_port_completed_in_the_body_is_never_flagged() { + let src = "module m (clk);\n input clk;\n logic clk;\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + assert!(violations("module m (clk);\n input wire clk;\nendmodule\n").is_empty()); + // An ANSI port redeclared in the body is left alone too, for the same + // reason: a rule that cannot tell the two apart must not accuse. + assert!(violations("module m (input logic clk);\n logic clk;\nendmodule\n").is_empty()); + } + + #[test] + fn a_prototype_and_its_definition_are_one_declaration() { + let src = "class c;\n extern function void f();\nendclass\n\ + function void c::f();\nendfunction\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + let forward = "package p;\n typedef class c;\n class c;\n endclass\nendpackage\n"; + assert!(violations(forward).is_empty(), "{:?}", violations(forward)); + } + + #[test] + fn conditional_arms_are_exclusive_so_they_are_not_flagged() { + let src = "module m;\n`ifdef X\n logic b;\n`else\n logic b;\n`endif\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_generate_scope_elaborates_one_arm_at_a_time() { + let src = "module m;\n\ + generate\n\ + if (A) begin : g\n\ + logic x;\n\ + end else begin : g\n\ + logic x;\n\ + end\n\ + endgenerate\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_name_reused_in_a_nested_scope_is_not_a_duplicate() { + // That is shadowing, which is `instance-shadowing`'s subject. + let src = + "module m;\n logic a;\n always_comb begin : blk\n logic a;\n end\nendmodule\n"; + assert!(violations(src).is_empty()); + // And two modules may each declare `a`. + let two = "module m;\n logic a;\nendmodule\nmodule n;\n logic a;\nendmodule\n"; + assert!(violations(two).is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/empty_item.rs b/crates/vlog_linter/src/rules/empty_item.rs index 5a0f549..88a9377 100644 --- a/crates/vlog_linter/src/rules/empty_item.rs +++ b/crates/vlog_linter/src/rules/empty_item.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::{Applicability, Fix, Violation}; use crate::visit::walk_items; use vlog_parser::ast::ItemKind; @@ -21,6 +22,10 @@ impl Rule for EmptyItem { "drop a `;` that stands where an item belongs" } + fn severity(&self) -> Severity { + Severity::Style + } + fn doc(&self) -> &'static str { "A lone `;` in a module, generate, package, interface, program or class \ body is a *null item* (IEEE 1800-2017 A.1.4). It is legal and it means \ diff --git a/crates/vlog_linter/src/rules/enum_name_style.rs b/crates/vlog_linter/src/rules/enum_name_style.rs index f0b16ed..d89b1eb 100644 --- a/crates/vlog_linter/src/rules/enum_name_style.rs +++ b/crates/vlog_linter/src/rules/enum_name_style.rs @@ -4,6 +4,7 @@ use crate::context::LintContext; use crate::naming::{is_escaped, is_lower_snake_case}; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use crate::visit::walk_items; use vlog_parser::ast::{ItemKind, TypedefKind}; @@ -22,6 +23,10 @@ impl Rule for EnumNameStyle { "name enum typedefs in lower_snake_case ending in _e or _t" } + fn severity(&self) -> Severity { + Severity::Style + } + fn doc(&self) -> &'static str { "A type name that looks like a type name is what makes a declaration \ readable at a glance: `state_e cur_state` says which identifier is the \ diff --git a/crates/vlog_linter/src/rules/explicit_function_task_parameter_type.rs b/crates/vlog_linter/src/rules/explicit_function_task_parameter_type.rs new file mode 100644 index 0000000..2f4b90f --- /dev/null +++ b/crates/vlog_linter/src/rules/explicit_function_task_parameter_type.rs @@ -0,0 +1,152 @@ +//! `explicit-function-task-parameter-type` — every formal gets a storage type. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_items; +use vlog_parser::ast::{ItemKind, TfArg}; + +/// See [`Rule::doc`]. +pub struct ExplicitFunctionTaskParameterType; + +const NAME: &str = "explicit-function-task-parameter-type"; + +impl Rule for ExplicitFunctionTaskParameterType { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "declare a storage type on every function and task argument" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "A task or function formal written without a type is a **one-bit \ + `logic`** (IEEE 1800 §13.3), so `function f(input a);` truncates \ + every caller's argument to its low bit and nothing complains — the \ + function simply returns the wrong answer for anything wider than a \ + flag. Verible's `explicit-function-task-parameter-type` (\"Checks \ + that every function and task parameter is declared with an explicit \ + storage type.\", enabled by default) is the same rule and the same \ + default. **A continuation formal inherits**: in `f(input int a, b)` \ + the `b` is an `int`, so only the argument that *opens* a declaration \ + — the first one, or the first after a direction keyword — is judged, \ + which is exactly the language's own rule. A DPI import's unnamed \ + formal (`import \"DPI-C\" function int f(int);`) names a type and no \ + identifier and is not this rule's subject. No automatic fix: only the \ + author knows how wide the argument was meant to be." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_items(ctx.file(), &mut |item| { + let (kw, args) = match &item.kind { + ItemKind::Function(decl) => ("function", &decl.args), + ItemKind::Task(decl) => ("task", &decl.args), + _ => return, + }; + out.extend(untyped(kw, args)); + }); + out + } +} + +/// The formals of one argument list that end up implicitly typed. +/// +/// Walked in order with the declaration's type carried along, which is how the +/// language reads them: a formal that writes a type sets it, a formal that +/// writes a direction keyword opens a new declaration (and so a new type, +/// implicit until written), and a formal that writes neither inherits whatever +/// is in force. +fn untyped(kw: &'static str, args: &[TfArg]) -> Vec { + let mut out = Vec::new(); + let mut opened = false; + for arg in args { + let opens = !opened || arg.dir.is_some() || !arg.ty.is_implicit(); + opened = true; + if !opens || !arg.ty.is_implicit() || arg.name.is_empty() { + continue; + } + out.push(Violation::new( + NAME, + format!("{kw} argument `{}` has no storage type; it is a 1-bit `logic`", arg.name), + arg.span, + )); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + ExplicitFunctionTaskParameterType.check(&LintContext::new(src, None)) + } + + fn wrap(header: &str) -> String { + format!("module m;\n {header}\n endfunction\nendmodule\n") + } + + #[test] + fn flags_an_untyped_formal() { + let src = wrap("function void f(input a);"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`a`"), "{}", found[0].message); + assert!(found[0].message.contains("1-bit"), "{}", found[0].message); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_typed_formal_is_what_the_rule_wants() { + for header in [ + "function void f(input logic a);", + "function void f(input int a);", + "function void f(input logic [7:0] a);", + "function void f(my_t a);", + "function void f();", + ] { + assert!( + violations(&wrap(header)).is_empty(), + "{header}: {:?}", + violations(&wrap(header)) + ); + } + } + + #[test] + fn a_continuation_formal_inherits_the_type_before_it() { + // `b` is an `int`, so only a genuinely untyped run may be reported. + assert!(violations(&wrap("function void f(input int a, b);")).is_empty()); + // ... and a new direction keyword opens a new, untyped declaration. + let found = violations(&wrap("function void f(input int a, output b);")); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`b`"), "{}", found[0].message); + } + + #[test] + fn a_task_is_judged_the_same_way() { + let src = "module m;\n task t(input a);\n endtask\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("task"), "{}", found[0].message); + } + + #[test] + fn an_unnamed_dpi_formal_is_not_this_rules_subject() { + let src = "import \"DPI-C\" function int f(int, chandle);\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_class_method_is_reached() { + let src = "class c;\n function void f(input a);\n endfunction\nendclass\n"; + assert_eq!(violations(src).len(), 1); + } +} diff --git a/crates/vlog_linter/src/rules/explicit_parameter_storage_type.rs b/crates/vlog_linter/src/rules/explicit_parameter_storage_type.rs index 4afcc99..87f8ce3 100644 --- a/crates/vlog_linter/src/rules/explicit_parameter_storage_type.rs +++ b/crates/vlog_linter/src/rules/explicit_parameter_storage_type.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use crate::visit::{walk_all_stmts, walk_items, walk_param_ports}; use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind}; @@ -20,6 +21,10 @@ impl Rule for ExplicitParameterStorageType { "declare a storage type on every parameter" } + fn severity(&self) -> Severity { + Severity::Style + } + fn doc(&self) -> &'static str { "A parameter with no declared type takes its type from whatever it is \ assigned — and an override at instantiation can change that type, not \ diff --git a/crates/vlog_linter/src/rules/forbid_defparam.rs b/crates/vlog_linter/src/rules/forbid_defparam.rs new file mode 100644 index 0000000..c3dbe5a --- /dev/null +++ b/crates/vlog_linter/src/rules/forbid_defparam.rs @@ -0,0 +1,93 @@ +//! `forbid-defparam` — `defparam` is deprecated; override at instantiation. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_items; +use vlog_parser::ast::ItemKind; + +/// See [`Rule::doc`]. +pub struct ForbidDefparam; + +const NAME: &str = "forbid-defparam"; + +impl Rule for ForbidDefparam { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "override a parameter at the instantiation, not with `defparam`" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "`defparam` reaches into another scope and changes a parameter there, \ + so the value a module elaborates with is written somewhere the module \ + does not name and a reader has no way to find without grepping the \ + whole design. It was deprecated in IEEE 1800-2009 (§A.11, and the LRM \ + says it may be removed from a future revision), several synthesis \ + tools reject it outright, and the `#(.NAME(value))` override at the \ + instantiation says the same thing where the instance is. Verible's \ + `forbid-defparam` (\"Do not use defparam.\", enabled by default) is \ + the same rule. No automatic fix: moving the value to the right \ + instantiation needs the instantiation, which may be in another file." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_items(ctx.file(), &mut |item| { + if matches!(item.kind, ItemKind::Defparam(_)) { + out.push(Violation::new( + NAME, + "`defparam` is deprecated; override the parameter at its instantiation", + item.span, + )); + } + }); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + ForbidDefparam.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_defparam_wherever_it_stands() { + let src = "module m;\n sub u ();\n defparam u.WIDTH = 8;\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "defparam u.WIDTH = 8;"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_named_override_is_what_the_rule_wants() { + assert!(violations("module m;\n sub #(.WIDTH(8)) u ();\nendmodule\n").is_empty()); + // Nor is a parameter declaration one. + assert!(violations("module m;\n parameter int WIDTH = 8;\nendmodule\n").is_empty()); + // And a signal that merely spells the word is not one either. + assert!(violations("module m;\n logic defparam_n;\nendmodule\n").is_empty()); + } + + #[test] + fn a_defparam_inside_generate_is_reached() { + let src = "module m;\n\ + generate\n\ + if (A) begin : g\n\ + defparam u.W = 1;\n\ + end\n\ + endgenerate\n\ + endmodule\n"; + assert_eq!(violations(src).len(), 1); + } +} diff --git a/crates/vlog_linter/src/rules/forbid_negative_array_dim.rs b/crates/vlog_linter/src/rules/forbid_negative_array_dim.rs new file mode 100644 index 0000000..3812f6a --- /dev/null +++ b/crates/vlog_linter/src/rules/forbid_negative_array_dim.rs @@ -0,0 +1,144 @@ +//! `forbid-negative-array-dim` — a negative literal inside a dimension. + +use crate::context::LintContext; +use crate::decls::walk_dims; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::ast::{DimKind, Expr, ExprKind}; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct ForbidNegativeArrayDim; + +const NAME: &str = "forbid-negative-array-dim"; + +impl Rule for ForbidNegativeArrayDim { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "do not write a negative constant in a dimension" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "`logic q [-1]` and `logic [-1:0] v` are what a parameter that came \ + out zero or one too small looks like after the subtraction: \ + `[WIDTH-1:0]` with `WIDTH = 0` is `[-1:0]`, which tools variously \ + reject, treat as empty, or size as two bits. Written as a literal it \ + is never intentional. Verible's `forbid-negative-array-dim` (\"Check \ + for negative constant literals inside array dimensions.\") is the \ + same rule; **lucisv turns it on by default where Verible ships it \ + off**, because a negative literal spelled out in a dimension has no \ + legitimate reading. Only a written `-` is flagged — an \ + expression that would *evaluate* negative needs the parameter values, \ + which lucisv does not have. No automatic fix." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_dims(ctx.file(), &mut |_, dim| { + let DimKind::Range { a, b } = &dim.kind else { return }; + for expr in [Some(a), b.as_ref()].into_iter().flatten() { + for span in negative_literals(expr) { + out.push(Violation::new(NAME, "negative constant in a dimension", span)); + } + } + }); + out.sort_by_key(|violation| (violation.span.start, violation.span.end)); + out + } +} + +/// The spans of every written `-` inside `expr`. +/// +/// A whole expression tree rather than the top node alone, because the shape +/// that turns up in real code is `[-1:0]` on one side and `[WIDTH-1:-1]` on +/// the other, and the offending term can sit anywhere in an arithmetic +/// expression. +fn negative_literals(expr: &Expr) -> Vec { + let mut out = Vec::new(); + collect(expr, &mut out); + out +} + +fn collect(expr: &Expr, out: &mut Vec) { + match &expr.kind { + ExprKind::Unary { op, expr: inner, .. } => { + if op == "-" && matches!(inner.kind, ExprKind::Number(_)) { + out.push(expr.span); + return; + } + collect(inner, out); + } + ExprKind::Binary { lhs, rhs, .. } => { + collect(lhs, out); + collect(rhs, out); + } + ExprKind::Paren { inner, .. } => collect(inner, out), + ExprKind::Ternary { cond, then, els, .. } => { + collect(cond, out); + collect(then, out); + collect(els, out); + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + ForbidNegativeArrayDim.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_negative_packed_bound() { + let src = "module m;\n logic [-1:0] v;\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "-1"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn flags_a_negative_unpacked_extent_and_one_buried_in_arithmetic() { + assert_eq!(violations("module m;\n logic q [-1];\nendmodule\n").len(), 1); + assert_eq!(violations("module m;\n logic [W + -2:0] v;\nendmodule\n").len(), 1); + // Both ends count. + assert_eq!(violations("module m;\n logic [-1:-2] v;\nendmodule\n").len(), 2); + } + + #[test] + fn ordinary_dimensions_are_silent() { + for decl in [ + "logic [7:0] v;", + "logic [WIDTH-1:0] v;", + "logic q [4];", + "logic q [0:3];", + "logic v;", + "logic q [];", + ] { + let src = format!("module m;\n {decl}\nendmodule\n"); + assert!(violations(&src).is_empty(), "{decl}: {:?}", violations(&src)); + } + } + + #[test] + fn a_negative_outside_a_dimension_is_not_this_rules_business() { + assert!(violations("module m;\n assign x = -1;\nendmodule\n").is_empty()); + assert!(violations("module m;\n parameter int P = -1;\nendmodule\n").is_empty()); + } + + #[test] + fn a_subtraction_is_not_a_negative_literal() { + // `WIDTH-1` is the ordinary way to write a width and must never fire. + assert!(violations("module m;\n logic [WIDTH-1:0] v;\nendmodule\n").is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/incomplete_assignment.rs b/crates/vlog_linter/src/rules/incomplete_assignment.rs new file mode 100644 index 0000000..a2423df --- /dev/null +++ b/crates/vlog_linter/src/rules/incomplete_assignment.rs @@ -0,0 +1,349 @@ +//! `incomplete-assignment` — a latch inferred in an `always_comb`. + +use std::collections::BTreeSet; + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::{walk_items, walk_stmts}; +use vlog_parser::ast::{Expr, ExprKind, ItemKind, Stmt, StmtKind}; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct IncompleteAssignment; + +const NAME: &str = "incomplete-assignment"; + +impl Rule for IncompleteAssignment { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "assign every variable on every path of an always_comb" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "A variable an `always_comb` writes on some paths and not on others \ + has to *hold its value* on the others, and holding a value is a \ + latch: the synthesized circuit grows storage nobody asked for, the \ + timing closes differently, and in simulation the block reads back \ + whatever it left there last time. `always_comb` was added to the \ + language precisely so tools could catch this, and most of them do — \ + but only at elaboration, long after the edit. There is no Verible \ + equivalent; this is TODO §33's own rule.\n\n\ + **Conservative by construction.** It speaks only about the \ + *top level* of an `always_comb` body, and only in the two shapes that \ + are unambiguous: an `if` with no `else`, and a `case` with no \ + `default`. A variable is reported only when the block writes it \ + inside such a statement and nothing **earlier in the block** already \ + covered it — where covering it means a plain assignment (a partial \ + one, through a bit select or a field, counts), or an `if`/`else` or a \ + `case` with a `default` that writes it in *every* arm. That last one \ + is the usual style, and the usual repair is the other: a default \ + assignment at the top of the block.\n\n\ + Everything else stays silent, deliberately: a name the block \ + **declares for itself** (a local temporary is not a latched output), \ + a left-hand side that is not a plain name or a concatenation of them, \ + a conditional nested inside another, and every `always` that is not \ + an `always_comb`. Measured on opentitan: three findings before those \ + exemptions, all three false, none after. No automatic fix: what the \ + missing branch should assign is a design decision." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_items(ctx.file(), &mut |item| { + let ItemKind::Always { kw, stmt } = &item.kind else { return }; + if kw != "always_comb" { + return; + } + out.extend(latches(ctx.source(), stmt)); + }); + out.sort_by_key(|violation| (violation.span.start, violation.span.end)); + out + } +} + +/// The findings of one `always_comb` body. +fn latches(source: &str, body: &Stmt) -> Vec { + // Names the block declares for itself are never reported: a temporary + // written inside the branch it was declared in is a local, not a latched + // output, and deciding which of the two it is needs elaboration. + let local = declared_names(body); + let mut covered: BTreeSet = BTreeSet::new(); + let mut out = Vec::new(); + for stmt in top_level(body) { + match &stmt.kind { + // Any write at all counts as coverage, a partial one included: a + // block that sets `cfg.mode` at the top and the whole `cfg` under + // an `if` has written the variable before the branch. + StmtKind::Assign { lhs, .. } => covered.extend(written_names(lhs)), + StmtKind::If { cond, then, els: None, .. } => { + let at = header(source, stmt.span, cond.span); + report(&mut out, &covered, &local, at, branch_names(then)); + } + // An `if` with an `else`, and a `case` with a `default`, cover + // every name their branches agree on — which is how the usual + // "assign it in every arm" style is written. + StmtKind::If { then, els: Some(els), .. } => { + covered.extend(intersect(&[branch_names(then), branch_names(els)])); + } + StmtKind::Case { expr, items, .. } => { + let per_branch: Vec> = + items.iter().map(|item| branch_names(&item.stmt)).collect(); + if items.iter().any(|item| item.labels.is_empty()) { + covered.extend(intersect(&per_branch)); + } else { + let mut names = BTreeSet::new(); + for branch in &per_branch { + names.extend(branch.iter().cloned()); + } + let at = header(source, stmt.span, expr.span); + report(&mut out, &covered, &local, at, names); + } + } + _ => {} + } + } + out +} + +/// The names every one of these branches writes. +fn intersect(branches: &[BTreeSet]) -> BTreeSet { + let Some((first, rest)) = branches.split_first() else { return BTreeSet::new() }; + first.iter().filter(|name| rest.iter().all(|set| set.contains(*name))).cloned().collect() +} + +/// Every name the block declares anywhere inside itself. +fn declared_names(body: &Stmt) -> BTreeSet { + let mut names = BTreeSet::new(); + walk_stmts(body, &mut |stmt| { + if let StmtKind::VarDecl(decl) = &stmt.kind { + names.extend(decl.declarators.iter().map(|d| d.name.clone())); + } + }); + names +} + +/// The statements written directly in the body — the body itself when it is +/// one statement, and a `begin ... end`'s own list when it is a block. +fn top_level(body: &Stmt) -> Vec<&Stmt> { + match &body.kind { + StmtKind::Block { stmts, .. } => stmts.iter().collect(), + // The body of an `always_comb` carries no timing control of its own, + // so anything else is a single statement standing as the whole block. + _ => vec![body], + } +} + +/// Every plain name a branch assigns, however deep inside it. +fn branch_names(stmt: &Stmt) -> BTreeSet { + let mut names = BTreeSet::new(); + walk_stmts(stmt, &mut |inner| { + if let StmtKind::Assign { lhs, .. } = &inner.kind { + names.extend(assigned_name(lhs)); + } + }); + names +} + +/// Adds one finding per name the branch writes that nothing covered before it +/// and that the block does not declare for itself. +fn report( + out: &mut Vec, + covered: &BTreeSet, + local: &BTreeSet, + span: TextRange, + names: BTreeSet, +) { + for name in names { + if covered.contains(&name) || local.contains(&name) { + continue; + } + out.push(Violation::new( + NAME, + format!("`{name}` is not assigned on every path; this infers a latch"), + span, + )); + } +} + +/// The `if (cond)` / `case (subject)` header alone, so a whole branch is not +/// painted red for a problem that lives on one line. The subject's own span +/// stops inside the parentheses, so the underline runs on to the `)` that +/// closes it — the same shape `case-missing-default` underlines. +fn header(source: &str, stmt: TextRange, subject: TextRange) -> TextRange { + let close = source + .get(subject.end as usize..) + .and_then(|rest| rest.find(')')) + .map(|i| subject.end + i as u32 + 1) + .unwrap_or(subject.end); + TextRange::new(stmt.start, close.max(stmt.start)) +} + +/// The plain name a left-hand side writes, or nothing when the target is not +/// one identifier. +/// +/// A bit or field select (`x[3] = …`, `s.f = …`) writes *part* of a variable, +/// and deciding whether the rest is covered needs ranges resolved — so those +/// are not names this rule will accuse. A concatenation lvalue is every name +/// in it, each of which is written whole. +fn assigned_name(lhs: &Expr) -> Vec { + match &lhs.kind { + ExprKind::Ident(name) => vec![name.clone()], + ExprKind::Concat(items) => { + items.iter().flat_map(|item| assigned_name(&item.expr)).collect() + } + _ => Vec::new(), + } +} + +/// Every name a left-hand side touches, a *part* of one included. +/// +/// The wider question — "was this variable written here at all?" — which is +/// what the coverage set wants: a block that writes `cfg.mode` before an `if` +/// that writes the whole `cfg` has already spoken for `cfg`, and reporting it +/// would be a latch that is not there. +fn written_names(lhs: &Expr) -> Vec { + match &lhs.kind { + ExprKind::Ident(name) => vec![name.clone()], + ExprKind::Concat(items) => { + items.iter().flat_map(|item| written_names(&item.expr)).collect() + } + ExprKind::Index { base, .. } + | ExprKind::Range { base, .. } + | ExprKind::Member { base, .. } => written_names(base), + _ => Vec::new(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + IncompleteAssignment.check(&LintContext::new(src, None)) + } + + fn wrap(body: &str) -> String { + format!("module m;\n always_comb begin\n{body} end\nendmodule\n") + } + + #[test] + fn flags_a_variable_written_only_under_an_if() { + let src = wrap(" if (en) y = a;\n"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`y`"), "{}", found[0].message); + assert_eq!(&src[found[0].span.as_range()], "if (en)", "the header, not the branch"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_default_assignment_before_the_if_is_the_repair() { + assert!(violations(&wrap(" y = 1'b0;\n if (en) y = a;\n")).is_empty()); + // ... and it must come *before*: assigning after the `if` does not + // stop the branch from inferring one. + assert_eq!(violations(&wrap(" if (en) y = a;\n y = 1'b0;\n")).len(), 1); + } + + #[test] + fn an_if_with_an_else_covers_every_path() { + assert!(violations(&wrap(" if (en) y = a; else y = b;\n")).is_empty()); + } + + #[test] + fn a_case_without_default_is_flagged_and_one_with_it_is_not() { + let with_default = " case (s)\n 0: y = a;\n default: y = b;\n endcase\n"; + assert!(violations(&wrap(with_default)).is_empty()); + let without = " case (s)\n 0: y = a;\n 1: y = b;\n endcase\n"; + let found = violations(&wrap(without)); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`y`"), "{}", found[0].message); + } + + #[test] + fn every_variable_of_a_branch_is_named_once() { + let found = violations(&wrap(" if (en) begin\n y = a;\n z = b;\n end\n")); + assert_eq!(found.len(), 2, "{found:?}"); + assert!(found[0].message.contains("`y`") || found[0].message.contains("`z`")); + // And a variable written twice in the branch is still one finding. + let twice = violations(&wrap(" if (en) begin\n y = a;\n y = b;\n end\n")); + assert_eq!(twice.len(), 1, "{twice:?}"); + } + + #[test] + fn only_always_comb_is_judged() { + for kw in ["always", "always_ff", "always_latch"] { + let src = format!("module m;\n {kw} @(posedge clk) if (en) y <= a;\nendmodule\n"); + assert!(violations(&src).is_empty(), "{kw}"); + } + assert!(violations("module m;\n always @* if (en) y = a;\nendmodule\n").is_empty()); + } + + #[test] + fn a_partial_write_is_not_accused() { + // Deciding whether the other bits are covered needs ranges resolved, + // which this rule does not do. + assert!(violations(&wrap(" if (en) y[3] = a;\n")).is_empty()); + assert!(violations(&wrap(" if (en) s.f = a;\n")).is_empty()); + } + + #[test] + fn a_concatenation_lvalue_names_every_target() { + let found = violations(&wrap(" if (en) {y, z} = a;\n")); + assert_eq!(found.len(), 2, "{found:?}"); + } + + #[test] + fn a_nested_conditional_is_left_to_the_top_level_one() { + // The outer `if` has an `else`, so the block covers every path as far + // as this rule is willing to claim. + let src = wrap(" if (en) begin\n if (x) y = a;\n end else y = b;\n"); + assert!(violations(&src).is_empty()); + } + + /// The three shapes the opentitan census turned up as false positives, each + /// pinned so it stays quiet. + #[test] + fn the_shapes_that_are_not_latches_stay_quiet() { + // 1. A variable the block declares for itself, written in the branch + // it was declared in (`entropy_src_core.sv`). + let local = wrap(" if (en) begin\n logic [3:0] tmp;\n tmp = a;\n end\n"); + assert!(violations(&local).is_empty(), "{:?}", violations(&local)); + + // 2. A partial write before the branch covers the variable + // (`kmac_app.sv`). + let partial = wrap(" cfg.mode = a;\n if (en) cfg = b;\n"); + assert!(violations(&partial).is_empty(), "{:?}", violations(&partial)); + + // 3. A `case` with a `default` that writes it in every arm, followed + // by an `if` that writes it again (`ibex_alu.sv`). + let after_case = wrap( + " case (s)\n 0: y = a;\n default: y = b;\n endcase\n\ + \x20 if (en) y = 1'b1;\n", + ); + assert!(violations(&after_case).is_empty(), "{:?}", violations(&after_case)); + } + + #[test] + fn an_if_else_before_the_branch_also_covers_it() { + let src = wrap(" if (a) y = 1; else y = 0;\n if (en) y = 2;\n"); + assert!(violations(&src).is_empty(), "{:?}", violations(&src)); + // ... but only for the names *both* arms write. + let partial = wrap(" if (a) y = 1; else z = 0;\n if (en) y = 2;\n"); + assert_eq!(violations(&partial).len(), 1, "{:?}", violations(&partial)); + } + + #[test] + fn a_body_that_is_one_statement_is_still_a_body() { + let src = "module m;\n always_comb if (en) y = a;\nendmodule\n"; + assert_eq!(violations(src).len(), 1); + } +} diff --git a/crates/vlog_linter/src/rules/instance_shadowing.rs b/crates/vlog_linter/src/rules/instance_shadowing.rs new file mode 100644 index 0000000..dfb7675 --- /dev/null +++ b/crates/vlog_linter/src/rules/instance_shadowing.rs @@ -0,0 +1,204 @@ +//! `instance-shadowing` — a declaration hiding one from an enclosing scope. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_semantic::{Scope, ScopeKind, Semantics, SymbolKind}; + +/// See [`Rule::doc`]. +pub struct InstanceShadowing; + +const NAME: &str = "instance-shadowing"; + +impl Rule for InstanceShadowing { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "do not hide an enclosing declaration with a new one of the same name" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "A `logic count;` inside a `begin : blk` where the module already has \ + a `count` compiles, and from then on every mention of `count` inside \ + the block means the inner one — including the ones written before the \ + inner declaration was added, which is how this arrives in a review \ + diff that looks like it changed nothing. Verible's `instance-\ + shadowing` (\"Warns if there are multiple declarations in the same \ + scope that shadow each other with the same name.\") is the same rule; \ + **lucisv turns it on by default where Verible ships it off**, because \ + the finding is always worth a second look and the repair is a rename \ + in one block.\n\n\ + Only the scopes **inside one design unit** are compared: a module, a \ + package or a class opens a fresh namespace, and a signal called `data` \ + in two different modules shadows nothing. A generate scope is \ + compared like any other block — the shadowing is real there too. No \ + automatic fix: renaming reaches every use inside the block." + } + + fn check(&self, ctx: &LintContext) -> Vec { + // Shadowing is a claim about *which scope* a name was declared in, + // and error recovery moves declarations between scopes — so a file + // that did not fully parse gets no opinion, exactly as + // `duplicate-declaration` gives it none. + if !ctx.parsed_cleanly() { + return Vec::new(); + } + let semantics = ctx.semantics(); + let mut out = Vec::new(); + for scope in semantics.scopes() { + if opens_a_unit(scope.kind) { + continue; + } + for &id in &scope.symbols { + let Some(symbol) = semantics.symbol(id) else { continue }; + let Some(hidden) = shadowed(semantics, scope, &symbol.name) else { continue }; + if !judged(symbol.kind) { + continue; + } + // The two are exclusive when a conditional-compilation + // directive stands between them, exactly as they are for + // `duplicate-declaration`. + if ctx.signals().conditional_between(&[hidden, symbol.name_span.start]) { + continue; + } + out.push(Violation::new( + NAME, + format!( + "`{}` shadows a declaration of the same name outside this scope", + symbol.name + ), + symbol.name_span, + )); + } + } + out.sort_by_key(|violation| (violation.span.start, violation.span.end)); + out + } +} + +/// The name span of the enclosing declaration `name` hides, if there is one +/// **within the same design unit**. +/// +/// The walk stops at the scope that opens a unit — a module, package or class +/// body — because a name declared in a different unit is reached by a +/// qualified path, never by shadowing. +fn shadowed(semantics: &Semantics, scope: &Scope, name: &str) -> Option { + let mut parent = scope.parent; + while let Some(id) = parent { + let outer = semantics.scope(id)?; + if let Some(hidden) = outer.lookup_local(name) { + return semantics.symbol(hidden).map(|symbol| symbol.name_span.start); + } + if opens_a_unit(outer.kind) { + return None; + } + parent = outer.parent; + } + None +} + +/// True for the scopes that open a design unit's own namespace. +fn opens_a_unit(kind: ScopeKind) -> bool { + matches!(kind, ScopeKind::File | ScopeKind::Module | ScopeKind::Package | ScopeKind::Class) +} + +/// True for the declarations worth reporting. +/// +/// A subroutine argument named after an enclosing signal is idiomatic +/// (`function automatic f(input logic clk)`), a block label is not a value, +/// and a `genvar` is scoped to its own loop by construction — so those stay +/// out. What is left is data and instances, which is where the surprise is. +fn judged(kind: SymbolKind) -> bool { + matches!( + kind, + SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance | SymbolKind::LocalParam + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + InstanceShadowing.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_block_local_that_hides_a_module_signal() { + let src = "module m;\n\ + logic count;\n\ + always_comb begin : blk\n\ + logic count;\n\ + count = 1'b0;\n\ + end\n\ + endmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`count`"), "{}", found[0].message); + assert!(found[0].span.start as usize > src.find("blk").unwrap_or(0), "the inner one"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_name_declared_once_is_never_flagged() { + let src = "module m;\n\ + logic count;\n\ + always_comb begin : blk\n\ + logic other;\n\ + end\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_different_unit_shadows_nothing() { + let src = "module a;\n logic data;\nendmodule\nmodule b;\n logic data;\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + // Nor does a package-level name reached from a module. + let pkg = "package p;\n logic data;\nendpackage\nmodule m;\n logic data;\nendmodule\n"; + assert!(violations(pkg).is_empty(), "{:?}", violations(pkg)); + } + + #[test] + fn a_generate_block_is_compared_like_any_other() { + let src = "module m;\n\ + logic x;\n\ + generate\n\ + if (A) begin : g\n\ + logic x;\n\ + end\n\ + endgenerate\n\ + endmodule\n"; + assert_eq!(violations(src).len(), 1, "{:?}", violations(src)); + } + + #[test] + fn a_subroutine_argument_named_after_a_signal_is_idiomatic() { + let src = "module m;\n\ + logic clk;\n\ + function automatic void f(input logic clk);\n\ + endfunction\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn conditional_arms_are_exclusive() { + let src = "module m;\n\ + logic x;\n\ + always_comb begin : blk\n\ + `ifdef A\n\ + logic x;\n\ + `endif\n\ + end\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/invalid_system_task_function.rs b/crates/vlog_linter/src/rules/invalid_system_task_function.rs new file mode 100644 index 0000000..39b3e56 --- /dev/null +++ b/crates/vlog_linter/src/rules/invalid_system_task_function.rs @@ -0,0 +1,132 @@ +//! `invalid-system-task-function` — system tasks nothing should still call. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::token::TokenKind; + +/// See [`Rule::doc`]. +pub struct InvalidSystemTaskFunction; + +const NAME: &str = "invalid-system-task-function"; + +/// The forbidden names and what to write instead — Verible's list +/// (`invalid-system-task-function`), name for name. +/// +/// The `$dist_*` family and `$random` all draw from the *global* seed that +/// `$random` shares, so one extra call anywhere in a testbench reshuffles +/// every other stream; `$urandom` and `$urandom_range` are per-thread and +/// reproducible. `$psprintf` is a vendor extension for the standard +/// `$sformatf`, and `$srandom` seeds that same global generator rather than +/// the calling process. +const FORBIDDEN: &[(&str, &str)] = &[ + ("$psprintf", "$sformatf"), + ("$random", "$urandom"), + ("$srandom", "process::self().srandom()"), + ("$dist_chi_square", "$urandom"), + ("$dist_erlang", "$urandom"), + ("$dist_exponential", "$urandom"), + ("$dist_normal", "$urandom"), + ("$dist_poisson", "$urandom"), + ("$dist_t", "$urandom"), + ("$dist_uniform", "$urandom"), +]; + +impl Rule for InvalidSystemTaskFunction { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "do not call a deprecated or non-reproducible system task" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "`$random`, `$srandom` and the `$dist_*` family all draw from one \ + global generator, so adding a call anywhere in a testbench reshuffles \ + every other random stream in it and a failing seed stops reproducing \ + — the reason IEEE 1800 added the per-process `$urandom` / \ + `$urandom_range` and `process::self().srandom()`. `$psprintf` is a \ + vendor spelling of the standard `$sformatf` and is not portable. \ + Verible's `invalid-system-task-function` (\"Checks that no forbidden \ + system tasks or functions are used.\", enabled by default) forbids \ + exactly this list, and lucisv names the replacement in the message. \ + No automatic fix: `$random` and `$urandom` return different value \ + streams, so swapping them changes what the test does." + } + + fn check(&self, ctx: &LintContext) -> Vec { + ctx.tokens() + .iter() + .filter(|token| token.kind == TokenKind::SystemIdent) + .filter_map(|token| { + let (name, instead) = + FORBIDDEN.iter().find(|(name, _)| *name == token.text.as_str())?; + Some(Violation::new( + NAME, + format!("`{name}` is forbidden; use `{instead}`"), + token.span, + )) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + InvalidSystemTaskFunction.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_every_forbidden_name_and_says_what_to_use() { + for (name, instead) in FORBIDDEN { + let src = format!("module m;\n initial x = {name}();\nendmodule\n"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{name}: {found:?}"); + assert!(found[0].message.contains(name), "{}", found[0].message); + assert!(found[0].message.contains(instead), "{}", found[0].message); + assert_eq!(&src[found[0].span.as_range()], *name, "the call, underlined"); + } + } + + #[test] + fn the_replacements_and_their_neighbours_are_left_alone() { + let src = "module m;\n\ + initial begin\n\ + a = $urandom();\n\ + b = $urandom_range(0, 7);\n\ + c = $sformatf(\"%0d\", a);\n\ + $display(\"%0d\", b);\n\ + end\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_near_miss_name_is_not_a_hit() { + // Matched whole, not by prefix: `$random_stable` and a signal called + // `random` are neither of them `$random`. + let src = "module m;\n\ + logic random;\n\ + initial begin\n\ + a = $randomize_helper();\n\ + b = random;\n\ + end\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_forbidden_name_inside_a_string_is_data() { + let src = "module m;\n initial $display(\"call $random here\");\nendmodule\n"; + assert!(violations(src).is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/mismatched_labels.rs b/crates/vlog_linter/src/rules/mismatched_labels.rs new file mode 100644 index 0000000..c96bc6a --- /dev/null +++ b/crates/vlog_linter/src/rules/mismatched_labels.rs @@ -0,0 +1,299 @@ +//! `mismatched-labels` — an end label that does not name its own block. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::{walk_all_stmts, walk_items}; +use vlog_parser::ast::{GenBlock, GenElse, Item, ItemKind, Name, StmtKind}; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct MismatchedLabels; + +const NAME: &str = "mismatched-labels"; + +impl Rule for MismatchedLabels { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "make an end label name the block it closes" + } + + fn severity(&self) -> Severity { + Severity::Error + } + + fn doc(&self) -> &'static str { + "`begin : fetch … end : decode` is a compile error (IEEE 1800 §9.3.4: \ + if both labels are given they must be identical), and so is an \ + `end : name` on a block that was never labelled. It is the classic \ + result of copying a block and renaming only one half — which is also \ + why it survives review: the two halves are pages apart. Verible's \ + `mismatched-labels` (\"Check for matching begin/end labels.\") is the \ + same rule; **lucisv turns it on by default where Verible ships it \ + off**, and files it as an **Error** rather than a style finding, \ + because the file does not compile.\n\n\ + Every construct that may carry a footer label is checked with one \ + answer: `module`/`interface`/`program`, `package`, `class`, \ + `function`, `task`, `begin`, `fork`/`join`, a generate block, a \ + `clocking` block, a `covergroup`, and a `property`/`sequence`. It is \ + a comparison of two spellings and nothing more, so an escaped \ + identifier is compared as written. No automatic fix: which of the two \ + names is the right one is exactly what a linter cannot know." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_items(ctx.file(), &mut |item| item_labels(&mut out, item)); + walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind { + StmtKind::Block { label, end_label, end_label_span, .. } => { + check_pair(&mut out, label.as_deref(), end_label.as_deref(), *end_label_span, "end") + } + StmtKind::ForkJoin { label, end_label, end_label_span, .. } => check_pair( + &mut out, + label.as_deref(), + end_label.as_deref(), + *end_label_span, + "join", + ), + _ => {} + }); + out.sort_by_key(|violation| (violation.span.start, violation.span.end)); + out + } +} + +/// The label pair one item carries, checked. One arm per construct that may +/// write a footer label, so a construct that gains one later has an obvious +/// place to go. +fn item_labels(out: &mut Vec, item: &Item) { + match &item.kind { + ItemKind::Module(module) => check_pair( + out, + Some(&module.name), + module.end_label.as_deref(), + module.end_label_span, + match module.kw.as_str() { + "interface" => "endinterface", + "program" => "endprogram", + _ => "endmodule", + }, + ), + ItemKind::Package { name, end_label, end_label_span, .. } => { + check_pair(out, Some(name), end_label.as_deref(), *end_label_span, "endpackage") + } + ItemKind::Class(class) => check_pair( + out, + Some(&class.name), + class.end_label.as_deref(), + class.end_label_span, + "endclass", + ), + ItemKind::Function(decl) => check_pair( + out, + Some(&decl.name), + decl.end_label.as_deref(), + decl.end_label_span, + "endfunction", + ), + ItemKind::Task(decl) => check_pair( + out, + Some(&decl.name), + decl.end_label.as_deref(), + decl.end_label_span, + "endtask", + ), + ItemKind::Clocking(decl) => check_pair( + out, + decl.name.as_ref().map(|name| name.text.as_str()), + decl.end_label.as_deref(), + decl.end_label_span, + "endclocking", + ), + ItemKind::Covergroup(decl) => { + check_name_pair(out, Some(&decl.name.text), decl.end_label.as_ref(), "endgroup") + } + ItemKind::PropSeqDecl(decl) => check_name_pair( + out, + Some(&decl.name.text), + decl.end_label.as_ref(), + if decl.kw == "sequence" { "endsequence" } else { "endproperty" }, + ), + // The item walk descends into a generate block's *items* but never + // visits the block itself, so its own label pair is collected here. + ItemKind::GenIf(gen_if) => { + check_gen_block(out, &gen_if.then); + let mut els = gen_if.els.as_deref(); + while let Some(branch) = els { + match branch { + GenElse::If(_, nested) => { + check_gen_block(out, &nested.then); + els = nested.els.as_deref(); + } + GenElse::Block(block) => { + check_gen_block(out, block); + els = None; + } + } + } + } + ItemKind::GenFor(gen_for) => check_gen_block(out, &gen_for.body), + ItemKind::GenCase(gen_case) => { + for case_item in &gen_case.items { + check_gen_block(out, &case_item.body); + } + } + _ => {} + } +} + +fn check_gen_block(out: &mut Vec, block: &GenBlock) { + check_pair( + out, + block.label.as_deref(), + block.end_label.as_deref(), + block.end_label_span, + "end", + ); +} + +/// Compares one header/footer pair, when a footer label was written at all. +fn check_pair( + out: &mut Vec, + opened: Option<&str>, + closed: Option<&str>, + at: Option, + kw: &'static str, +) { + let (Some(closed), Some(at)) = (closed, at) else { return }; + if at.is_empty() { + return; + } + let message = match opened { + Some(opened) if opened == closed => return, + Some(opened) => format!("`{kw} : {closed}` closes `{opened}`"), + None => format!("`{kw} : {closed}` closes a block with no label"), + }; + out.push(Violation::new(NAME, message, at)); +} + +/// The same, for the constructs whose footer label is a [`Name`]. +fn check_name_pair( + out: &mut Vec, + opened: Option<&str>, + closed: Option<&Name>, + kw: &'static str, +) { + check_pair( + out, + opened, + closed.map(|name| name.text.as_str()), + closed.map(|name| name.span), + kw, + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + MismatchedLabels.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_footer_that_names_another_block() { + let src = "module m;\n\ + always_comb begin : fetch\n\ + x = 1;\n\ + end : decode\n\ + endmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "decode"); + assert!(found[0].message.contains("fetch"), "{}", found[0].message); + assert!(found[0].fix.is_none()); + } + + #[test] + fn flags_a_footer_label_on_an_unlabelled_block() { + let src = "module m;\n always_comb begin\n x = 1;\n end : blk\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("no label"), "{}", found[0].message); + } + + #[test] + fn a_matching_pair_and_a_missing_footer_are_both_fine() { + for src in [ + "module m;\n always_comb begin : blk\n x = 1;\n end : blk\nendmodule\n", + "module m;\n always_comb begin : blk\n x = 1;\n end\nendmodule\n", + "module m;\n always_comb begin\n x = 1;\n end\nendmodule\n", + "module m;\nendmodule : m\n", + ] { + assert!(violations(src).is_empty(), "{src}: {:?}", violations(src)); + } + } + + #[test] + fn every_construct_with_a_footer_label_is_checked() { + for (src, wrong) in [ + ("module m;\nendmodule : other\n", "other"), + ("interface i;\nendinterface : other\n", "other"), + ("package p;\nendpackage : other\n", "other"), + ("class c;\nendclass : other\n", "other"), + ("module m;\n function void f();\n endfunction : other\nendmodule\n", "other"), + ("module m;\n task t();\n endtask : other\nendmodule\n", "other"), + ( + "interface i;\n clocking cb @(posedge clk);\n endclocking : other\nendinterface\n", + "other", + ), + ( + "module m;\n covergroup cg;\n endgroup : other\nendmodule\n", + "other", + ), + ( + "module m;\n property p;\n a |-> b;\n endproperty : other\nendmodule\n", + "other", + ), + ] { + let found = violations(src); + assert_eq!(found.len(), 1, "{src}: {found:?}"); + assert_eq!(&src[found[0].span.as_range()], wrong, "{src}"); + } + } + + #[test] + fn a_fork_join_and_a_generate_block_are_checked() { + let fork = "module m;\n\ + initial fork : spawn\n\ + x = 1;\n\ + join : other\n\ + endmodule\n"; + assert_eq!(violations(fork).len(), 1, "{:?}", violations(fork)); + + let generate = "module m;\n\ + generate\n\ + if (A) begin : g\n\ + wire a;\n\ + end : other\n\ + endgenerate\n\ + endmodule\n"; + assert_eq!(violations(generate).len(), 1, "{:?}", violations(generate)); + } + + #[test] + fn a_nested_block_is_matched_against_its_own_header() { + let src = "module m;\n\ + always_comb begin : outer\n\ + begin : inner\n\ + x = 1;\n\ + end : inner\n\ + end : outer\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/mod.rs b/crates/vlog_linter/src/rules/mod.rs index eecdd84..0a38208 100644 --- a/crates/vlog_linter/src/rules/mod.rs +++ b/crates/vlog_linter/src/rules/mod.rs @@ -1,24 +1,45 @@ //! The rules themselves, one module each. //! -//! Most rules are **syntactic** — text, tokens or tree shape. The three that -//! are not (`unused-signal`, `undriven-net`, `multiply-driven`) read the -//! symbol table through `crate::signals`; see -//! `docs/features/semantic-lints/README.md`. +//! Most rules are **syntactic** — text, tokens or tree shape. The ones that +//! are not read the symbol table: `unused-signal`, `undriven-net` and +//! `multiply-driven` through `crate::signals` (see +//! `docs/features/semantic-lints/README.md`), and `duplicate-declaration` and +//! `instance-shadowing` through `vlog_semantic::Semantics` directly (see +//! `docs/features/linter-expansion-1/README.md`). pub mod always_comb_blocking; pub mod always_ff_non_blocking; pub mod case_missing_default; +pub mod duplicate_declaration; pub mod empty_item; pub mod enum_name_style; +pub mod explicit_function_task_parameter_type; pub mod explicit_parameter_storage_type; +pub mod forbid_defparam; +pub mod forbid_negative_array_dim; +pub mod incomplete_assignment; +pub mod instance_shadowing; +pub mod invalid_system_task_function; +pub mod mismatched_labels; pub mod module_filename; pub mod module_name_style; +pub mod module_parameter; +pub mod module_port; pub mod multiply_driven; pub mod no_tabs; pub mod no_trailing_whitespace; +pub mod packed_dimensions_range_ordering; pub mod parameter_name_style; +pub mod plusarg_assignment; pub mod struct_union_name_style; +pub mod suspicious_semicolon; +pub mod truncated_numeric_literal; +pub mod undeclared_identifier; +pub mod undersized_binary_literal; pub mod undriven_net; +pub mod unknown_parameter; +pub mod unknown_port; pub mod unused_signal; pub mod unused_waiver; +pub mod void_cast; pub mod wire_reg_mixup; diff --git a/crates/vlog_linter/src/rules/module_filename.rs b/crates/vlog_linter/src/rules/module_filename.rs index 9c8d867..6b50d64 100644 --- a/crates/vlog_linter/src/rules/module_filename.rs +++ b/crates/vlog_linter/src/rules/module_filename.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use vlog_parser::ast::ItemKind; @@ -19,6 +20,10 @@ impl Rule for ModuleFilename { "name a one-module file after its module" } + fn severity(&self) -> Severity { + Severity::Style + } + fn doc(&self) -> &'static str { "Every Verilog tool that finds a module by searching a library \ directory — simulators, synthesis `-y` paths, most build systems — \ diff --git a/crates/vlog_linter/src/rules/module_name_style.rs b/crates/vlog_linter/src/rules/module_name_style.rs index c72ae76..47df879 100644 --- a/crates/vlog_linter/src/rules/module_name_style.rs +++ b/crates/vlog_linter/src/rules/module_name_style.rs @@ -3,6 +3,7 @@ use crate::context::LintContext; use crate::naming::{is_escaped, is_lower_snake_case}; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use crate::visit::walk_items; use vlog_parser::ast::ItemKind; @@ -21,6 +22,10 @@ impl Rule for ModuleNameStyle { "name modules in lower_snake_case" } + fn severity(&self) -> Severity { + Severity::Style + } + fn doc(&self) -> &'static str { "A module name ends up as a file name, a directory name, an instance \ path in a waveform viewer and a grep target, and every one of those is \ diff --git a/crates/vlog_linter/src/rules/module_parameter.rs b/crates/vlog_linter/src/rules/module_parameter.rs new file mode 100644 index 0000000..2659632 --- /dev/null +++ b/crates/vlog_linter/src/rules/module_parameter.rs @@ -0,0 +1,101 @@ +//! `module-parameter` — override a multi-parameter instance by name. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_instantiations; + +/// See [`Rule::doc`]. +pub struct ModuleParameter; + +const NAME: &str = "module-parameter"; + +impl Rule for ModuleParameter { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "override more than one parameter by name" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "`sub #(8, 4) u ()` binds by *order*, so a parameter added to the \ + instantiated module — or two of them reordered — silently changes \ + what every instance elaborates to, and two integers in a row give a \ + reader nothing to check against. `#(.Width(8), .Depth(4))` names each \ + one where it is written. Verible's `module-parameter` (\"Checks that \ + module instantiations with more than one parameter are passed in as \ + named parameters.\", enabled by default) is the same rule and the \ + same default; a single positional override is left alone by both. No \ + automatic fix: the names live in the instantiated module, usually in \ + another file." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_instantiations(ctx.file(), &mut |inst| { + let Some(params) = &inst.params else { return }; + let positional = params.iter().filter(|conn| conn.name.is_empty()).count(); + if positional < 2 { + return; + } + out.push(Violation::new( + NAME, + format!("`{}` takes {positional} parameters by position; name them", inst.module), + inst.module_span, + )); + }); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + ModuleParameter.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_more_than_one_positional_override() { + let src = "module m;\n sub #(8, 4) u_sub ();\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`sub`"), "{}", found[0].message); + assert!(found[0].message.contains("2 parameters"), "{}", found[0].message); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_named_override_is_what_the_rule_wants() { + let src = "module m;\n sub #(.Width(8), .Depth(4)) u_sub ();\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn one_override_or_none_has_no_order_to_get_wrong() { + assert!(violations("module m;\n sub #(8) u ();\nendmodule\n").is_empty()); + assert!(violations("module m;\n sub #() u ();\nendmodule\n").is_empty()); + assert!(violations("module m;\n sub u ();\nendmodule\n").is_empty()); + } + + #[test] + fn a_bind_and_a_generate_body_are_both_reached() { + assert_eq!(violations("bind top sub #(8, 4) u ();\n").len(), 1); + let generate = "module m;\n\ + generate\n\ + if (A) begin : g\n\ + sub #(8, 4) u ();\n\ + end\n\ + endgenerate\n\ + endmodule\n"; + assert_eq!(violations(generate).len(), 1); + } +} diff --git a/crates/vlog_linter/src/rules/module_port.rs b/crates/vlog_linter/src/rules/module_port.rs new file mode 100644 index 0000000..e5542e0 --- /dev/null +++ b/crates/vlog_linter/src/rules/module_port.rs @@ -0,0 +1,119 @@ +//! `module-port` — connect a multi-port instance by name. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_instantiations; +use vlog_parser::ast::Connections; + +/// See [`Rule::doc`]. +pub struct ModulePort; + +const NAME: &str = "module-port"; + +impl Rule for ModulePort { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "connect an instance with more than one port by name" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "A positional connection list binds by *order*, so inserting a port in \ + the instantiated module silently rewires every instance of it — and \ + two ports of the same width swapped by hand compile perfectly and \ + fail in simulation. A named list (`.clk_i(clk)`) says what is \ + connected to what at the site, breaks loudly when a port is renamed, \ + and is what every reviewer can check without opening the other file. \ + Verible's `module-port` (\"Checks that module instantiations with \ + more than one port are passed in as named ports.\", enabled by \ + default) is the same rule and the same default; a single-port \ + instance is left alone by both, because there is no order to get \ + wrong. No automatic fix: naming the ports needs the instantiated \ + module's port list, which is usually in another file." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_instantiations(ctx.file(), &mut |inst| { + for instance in &inst.instances { + let Connections::Ordered(conns) = &instance.conns else { continue }; + if conns.len() < 2 { + continue; + } + out.push(Violation::new( + NAME, + format!( + "`{}` is connected by position; name its {} ports", + inst.module, + conns.len() + ), + instance.span, + )); + } + }); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + ModulePort.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_positional_list_of_more_than_one() { + let src = "module m;\n sub u_sub (a, b, c);\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`sub`"), "{}", found[0].message); + assert!(found[0].message.contains("3 ports"), "{}", found[0].message); + assert_eq!(&src[found[0].span.as_range()], "u_sub (a, b, c)"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_named_list_is_what_the_rule_wants() { + let src = "module m;\n sub u_sub (.a(x), .b(y), .c(z));\nendmodule\n"; + assert!(violations(src).is_empty()); + // `.*` is a named list too. + assert!(violations("module m;\n sub u_sub (.*);\nendmodule\n").is_empty()); + } + + #[test] + fn one_port_or_none_has_no_order_to_get_wrong() { + assert!(violations("module m;\n sub u_sub (a);\nendmodule\n").is_empty()); + assert!(violations("module m;\n sub u_sub ();\nendmodule\n").is_empty()); + } + + #[test] + fn every_instance_of_one_statement_is_judged() { + let src = "module m;\n sub u1 (a, b), u2 (.a(x), .b(y)), u3 (c, d);\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 2, "{found:?}"); + assert!(found[0].span.start < found[1].span.start, "in source order"); + } + + #[test] + fn an_instantiation_inside_generate_and_a_bind_are_both_reached() { + let generate = "module m;\n\ + generate\n\ + if (A) begin : g\n\ + sub u (a, b);\n\ + end\n\ + endgenerate\n\ + endmodule\n"; + assert_eq!(violations(generate).len(), 1); + assert_eq!(violations("bind top sub u (a, b);\n").len(), 1); + } +} diff --git a/crates/vlog_linter/src/rules/multiply_driven.rs b/crates/vlog_linter/src/rules/multiply_driven.rs index 0598f84..9853598 100644 --- a/crates/vlog_linter/src/rules/multiply_driven.rs +++ b/crates/vlog_linter/src/rules/multiply_driven.rs @@ -4,6 +4,7 @@ use std::collections::BTreeSet; use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::signals::{Driver, DriverKind}; use crate::violation::Violation; @@ -21,6 +22,10 @@ impl Rule for MultiplyDriven { "give a variable exactly one driver" } + fn severity(&self) -> Severity { + Severity::Error + } + fn doc(&self) -> &'static str { "A SystemVerilog *variable* — `logic`, `reg`, `int` — may be written \ from one source only (IEEE 1800 §6.5). Two `always` blocks assigning \ diff --git a/crates/vlog_linter/src/rules/no_tabs.rs b/crates/vlog_linter/src/rules/no_tabs.rs index 499ea08..211c9e3 100644 --- a/crates/vlog_linter/src/rules/no_tabs.rs +++ b/crates/vlog_linter/src/rules/no_tabs.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::{Applicability, Fix, Violation}; use vlog_parser::span::TextRange; @@ -19,6 +20,10 @@ impl Rule for NoTabs { "use spaces, not tabs" } + fn severity(&self) -> Severity { + Severity::Style + } + fn doc(&self) -> &'static str { "A tab renders at a width nobody agrees on, so a file mixing tabs and \ spaces looks aligned in the editor that wrote it and ragged everywhere \ diff --git a/crates/vlog_linter/src/rules/no_trailing_whitespace.rs b/crates/vlog_linter/src/rules/no_trailing_whitespace.rs index cc89d65..90fcecc 100644 --- a/crates/vlog_linter/src/rules/no_trailing_whitespace.rs +++ b/crates/vlog_linter/src/rules/no_trailing_whitespace.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::{Applicability, Fix, Violation}; use vlog_parser::span::TextRange; @@ -19,6 +20,10 @@ impl Rule for NoTrailingWhitespace { "no whitespace at the end of a line" } + fn severity(&self) -> Severity { + Severity::Style + } + fn doc(&self) -> &'static str { "Trailing whitespace is invisible, so it survives review and then shows \ up as diff noise the day somebody's editor strips it — a one-character \ diff --git a/crates/vlog_linter/src/rules/packed_dimensions_range_ordering.rs b/crates/vlog_linter/src/rules/packed_dimensions_range_ordering.rs new file mode 100644 index 0000000..631cdbd --- /dev/null +++ b/crates/vlog_linter/src/rules/packed_dimensions_range_ordering.rs @@ -0,0 +1,149 @@ +//! `packed-dimensions-range-ordering` — write a vector's width `[N-1:0]`. + +use crate::context::LintContext; +use crate::decls::{walk_dims, Packing}; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::ast::{DimKind, Expr, ExprKind}; + +/// See [`Rule::doc`]. +pub struct PackedDimensionsRangeOrdering; + +const NAME: &str = "packed-dimensions-range-ordering"; + +impl Rule for PackedDimensionsRangeOrdering { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "declare a packed dimension in decreasing order, `[N-1:0]`" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "`logic [0:7] data` is legal and means bit 0 is the *most* significant \ + one, so `data[0]` is the top bit, a part select counts the other way \ + and every concatenation with an ordinary `[7:0]` vector silently \ + reverses. Nothing in the language stops it and no tool warns; the \ + cost lands on whoever reads the two declarations side by side. \ + Verible's `packed-dimensions-range-ordering` (\"Checks that packed \ + dimension ranges are declare in little-endian (decreasing) order, \ + e.g. `[N-1:0]`.\", enabled by default) is the same rule and the same \ + default. **Only packed dimensions are judged**: an unpacked `[0:3]` \ + array is an ordinary ascending array and is a perfectly normal thing \ + to write. A range is flagged when both bounds are integer literals \ + and the left one is smaller, and when the left one is a literal `0` \ + and the right is anything else — every other shape is left alone, \ + because lucisv does not evaluate parameters. No automatic fix: \ + reversing a range reverses every use of it." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_dims(ctx.file(), &mut |packing, dim| { + if packing != Packing::Packed { + return; + } + let DimKind::Range { a, b: Some(b) } = &dim.kind else { return }; + if !ascending(a, b) { + return; + } + out.push(Violation::new( + NAME, + "packed dimension counts upwards; write it as `[N-1:0]`", + dim.span, + )); + }); + out + } +} + +/// True when `[a:b]` demonstrably counts upwards. +/// +/// Two literals decide it outright. A left bound of literal `0` decides it too +/// whatever the right bound is — `[0:WIDTH-1]` is the shape this rule mostly +/// meets — unless the right bound is `0` as well, which is the one-bit +/// `[0:0]` and counts in no direction at all. Anything else is two symbolic +/// bounds lucisv cannot compare, and it says nothing. +fn ascending(a: &Expr, b: &Expr) -> bool { + match (literal(a), literal(b)) { + (Some(left), Some(right)) => left < right, + (Some(0), None) => true, + _ => false, + } +} + +/// The value of a plain unsigned integer literal, or `None` for anything else. +fn literal(expr: &Expr) -> Option { + let ExprKind::Number(text) = &expr.kind else { return None }; + if text.contains(['\'', '.']) { + return None; + } + text.chars().filter(|c| *c != '_').collect::().parse().ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + PackedDimensionsRangeOrdering.check(&LintContext::new(src, None)) + } + + fn decl(ty: &str) -> String { + format!("module m;\n {ty} sig;\nendmodule\n") + } + + #[test] + fn flags_an_ascending_packed_range() { + let src = decl("logic [0:7]"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "[0:7]"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn flags_the_common_zero_to_symbolic_shape() { + assert_eq!(violations(&decl("logic [0:WIDTH-1]")).len(), 1); + assert_eq!(violations(&decl("logic [1:2]")).len(), 1); + } + + #[test] + fn a_decreasing_range_is_what_the_rule_wants() { + for ty in ["logic [7:0]", "logic [WIDTH-1:0]", "logic [0:0]", "logic", "logic [3]"] { + assert!(violations(&decl(ty)).is_empty(), "{ty}: {:?}", violations(&decl(ty))); + } + } + + #[test] + fn two_symbolic_bounds_are_left_alone() { + // lucisv does not evaluate parameters, so it says nothing here rather + // than guessing which way `LO:HI` counts. + assert!(violations(&decl("logic [LO:HI]")).is_empty()); + assert!(violations(&decl("logic [A-1:B]")).is_empty()); + } + + #[test] + fn an_unpacked_array_is_not_a_packed_dimension() { + assert!(violations("module m;\n logic q [0:3];\nendmodule\n").is_empty()); + assert!(violations("module m;\n logic [7:0] q [0:3];\nendmodule\n").is_empty()); + } + + #[test] + fn every_declaration_shape_is_reached() { + let src = "module m #(parameter logic [0:1] P = 0) (\n\ + input logic [0:2] a\n\ + );\n\ + typedef logic [0:3] w_t;\n\ + function void f(input logic [0:4] x);\n\ + endfunction\n\ + endmodule\n"; + assert_eq!(violations(src).len(), 4, "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/parameter_name_style.rs b/crates/vlog_linter/src/rules/parameter_name_style.rs index 93a784b..db76fdb 100644 --- a/crates/vlog_linter/src/rules/parameter_name_style.rs +++ b/crates/vlog_linter/src/rules/parameter_name_style.rs @@ -3,6 +3,7 @@ use crate::context::LintContext; use crate::naming::{is_camel_case, is_escaped, is_upper_snake_case}; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use crate::visit::{walk_all_stmts, walk_items, walk_param_ports}; use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind}; @@ -22,6 +23,10 @@ impl Rule for ParameterNameStyle { "name parameters in CamelCase or ALL_CAPS" } + fn severity(&self) -> Severity { + Severity::Style + } + fn doc(&self) -> &'static str { "A parameter is a compile-time constant, and reading one at a use site \ should not require scrolling back to the declaration to learn that. \ diff --git a/crates/vlog_linter/src/rules/plusarg_assignment.rs b/crates/vlog_linter/src/rules/plusarg_assignment.rs new file mode 100644 index 0000000..cb6eda4 --- /dev/null +++ b/crates/vlog_linter/src/rules/plusarg_assignment.rs @@ -0,0 +1,88 @@ +//! `plusarg-assignment` — read a plusarg's value, do not test for its name. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::token::TokenKind; + +/// See [`Rule::doc`]. +pub struct PlusargAssignment; + +const NAME: &str = "plusarg-assignment"; + +/// The system task this rule is about. +const TEST_PLUSARGS: &str = "$test$plusargs"; + +impl Rule for PlusargAssignment { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "read a plusarg with `$value$plusargs`, not `$test$plusargs`" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "`$test$plusargs(\"foo\")` answers only whether `+foo` was on the \ + command line, and it matches by *prefix*: `+foobar` makes it true \ + too, so two switches that share a prefix silently turn each other on. \ + `$value$plusargs(\"foo=%d\", v)` matches the whole name, says whether \ + it was there, and hands back the value — everything the other one \ + does, without the trap, which is why a plusarg should always be \ + given and read as a value. Verible's `plusarg-assignment` (\"Checks \ + that plusargs are always assigned a value, by ensuring that plusargs \ + are never accessed using the `$test$plusargs` system task.\", enabled \ + by default) is the same rule and the same default. No automatic fix: \ + the replacement needs a format string and a variable to read into, \ + neither of which the call being replaced has." + } + + fn check(&self, ctx: &LintContext) -> Vec { + ctx.tokens() + .iter() + .filter(|token| token.kind == TokenKind::SystemIdent && token.text == TEST_PLUSARGS) + .map(|token| { + Violation::new( + NAME, + "`$test$plusargs` matches by prefix; use `$value$plusargs` and read the value", + token.span, + ) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + PlusargAssignment.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_test_plusargs_call() { + let src = "module m;\n initial if ($test$plusargs(\"fast\")) go = 1;\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "$test$plusargs"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn the_value_form_is_what_the_rule_wants() { + let src = "module m;\n\ + initial if ($value$plusargs(\"speed=%0d\", speed)) go = 1;\n\ + endmodule\n"; + assert!(violations(src).is_empty()); + // And a name that merely contains the words is not the call. + assert!(violations("module m;\n logic test_plusargs;\nendmodule\n").is_empty()); + assert!(violations("module m;\n initial $display(\"$test$plusargs\");\nendmodule\n") + .is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/struct_union_name_style.rs b/crates/vlog_linter/src/rules/struct_union_name_style.rs index 1f45430..6d8a275 100644 --- a/crates/vlog_linter/src/rules/struct_union_name_style.rs +++ b/crates/vlog_linter/src/rules/struct_union_name_style.rs @@ -4,6 +4,7 @@ use crate::context::LintContext; use crate::naming::{is_escaped, is_lower_snake_case}; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use crate::visit::walk_items; use vlog_parser::ast::{ItemKind, TypedefKind}; @@ -22,6 +23,10 @@ impl Rule for StructUnionNameStyle { "name struct and union typedefs in lower_snake_case ending in _t" } + fn severity(&self) -> Severity { + Severity::Style + } + fn doc(&self) -> &'static str { "The `_t` suffix is the one piece of Verilog naming convention that is \ nearly universal: it marks an identifier as a type, which the language \ diff --git a/crates/vlog_linter/src/rules/suspicious_semicolon.rs b/crates/vlog_linter/src/rules/suspicious_semicolon.rs new file mode 100644 index 0000000..00167b5 --- /dev/null +++ b/crates/vlog_linter/src/rules/suspicious_semicolon.rs @@ -0,0 +1,168 @@ +//! `suspicious-semicolon` — a `;` where a body was meant. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_all_stmts; +use vlog_parser::ast::{Stmt, StmtKind}; + +/// See [`Rule::doc`]. +pub struct SuspiciousSemicolon; + +const NAME: &str = "suspicious-semicolon"; + +impl Rule for SuspiciousSemicolon { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "do not end a control statement's header with a `;`" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "`if (ready);` is legal and does nothing: the `;` is the whole body, \ + and whatever is indented under it runs unconditionally. The same \ + typo turns `for (…);` and `while (…);` into a loop that spins on an \ + empty body — an infinite one, if the body was where the loop variable \ + moved. It survives review because it looks right; the character that \ + breaks it is one column wide. Verible's `suspicious-semicolon` \ + (\"Checks that there are no suspicious semicolons that might affect \ + code behaviour but escape quick visual inspection.\") is the same \ + rule; **lucisv turns it on by default where Verible ships it off**, \ + because the finding is a typo rather than a matter of taste. A \ + deliberately empty body is written `begin end`, which is not \ + reported. No automatic fix: deleting the `;` would change what the \ + code does, and that is the author's call." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_all_stmts(ctx.file(), &mut |stmt| { + for (what, body) in empty_bodies(stmt) { + out.push(Violation::new( + NAME, + format!("`{what}` has an empty body; the `;` is the whole of it"), + body.span, + )); + } + }); + out + } +} + +/// The null bodies of one statement: what it is, and the `;` standing where +/// its body belongs. A statement with a real body contributes nothing. +fn empty_bodies(stmt: &Stmt) -> Vec<(&'static str, &Stmt)> { + let null = |body: &Stmt| matches!(body.kind, StmtKind::Null); + let mut out = Vec::new(); + match &stmt.kind { + StmtKind::If { then, els, .. } => { + if null(then) { + out.push(("if", then.as_ref())); + } + // An `else if` is an `if` and is judged as one when the walk + // reaches it; only a bare `else ;` is this statement's fault. + if let Some(els) = els { + if null(els) { + out.push(("else", els.as_ref())); + } + } + } + StmtKind::For { body, .. } => push_if(&mut out, "for", body, null), + StmtKind::While { body, .. } => push_if(&mut out, "while", body, null), + StmtKind::Repeat { body, .. } => push_if(&mut out, "repeat", body, null), + StmtKind::Forever { body } => push_if(&mut out, "forever", body, null), + StmtKind::Foreach { body, .. } => push_if(&mut out, "foreach", body, null), + _ => {} + } + out +} + +fn push_if<'a>( + out: &mut Vec<(&'static str, &'a Stmt)>, + what: &'static str, + body: &'a Stmt, + null: impl Fn(&Stmt) -> bool, +) { + if null(body) { + out.push((what, body)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + SuspiciousSemicolon.check(&LintContext::new(src, None)) + } + + fn wrap(body: &str) -> String { + format!("module m;\n always_comb begin\n{body} end\nendmodule\n") + } + + #[test] + fn flags_an_if_whose_body_is_a_semicolon() { + let src = wrap(" if (ready);\n x = 1;\n"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`if`"), "{}", found[0].message); + assert_eq!(&src[found[0].span.as_range()], ";", "the `;`, underlined"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn flags_every_loop_header_and_a_bare_else() { + for (body, what) in [ + (" for (int i = 0; i < 4; i++);\n", "for"), + (" while (busy);\n", "while"), + (" repeat (4);\n", "repeat"), + (" forever;\n", "forever"), + (" foreach (q[i]);\n", "foreach"), + (" if (a) x = 1; else;\n", "else"), + ] { + let found = violations(&wrap(body)); + assert_eq!(found.len(), 1, "{body}: {found:?}"); + assert!(found[0].message.contains(what), "{}", found[0].message); + } + } + + #[test] + fn a_real_body_is_never_flagged() { + for body in [ + " if (ready) x = 1;\n", + " if (ready) begin\n x = 1;\n end\n", + " if (a) x = 1; else x = 0;\n", + " while (busy) x = 1;\n", + " for (int i = 0; i < 4; i++) x = i;\n", + ] { + assert!(violations(&wrap(body)).is_empty(), "{body}"); + } + } + + #[test] + fn a_deliberately_empty_block_is_the_way_to_write_one() { + assert!(violations(&wrap(" if (ready) begin end\n")).is_empty()); + assert!(violations(&wrap(" forever begin end\n")).is_empty()); + } + + #[test] + fn a_lone_null_statement_is_not_a_body() { + // A stray `;` among statements is harmless — it is nobody's body. + assert!(violations(&wrap(" ;\n x = 1;\n")).is_empty()); + } + + #[test] + fn an_else_if_chain_is_judged_on_the_inner_if() { + let src = wrap(" if (a) x = 1; else if (b);\n"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`if`"), "{}", found[0].message); + } +} diff --git a/crates/vlog_linter/src/rules/truncated_numeric_literal.rs b/crates/vlog_linter/src/rules/truncated_numeric_literal.rs new file mode 100644 index 0000000..0c44b2f --- /dev/null +++ b/crates/vlog_linter/src/rules/truncated_numeric_literal.rs @@ -0,0 +1,156 @@ +//! `truncated-numeric-literal` — a literal wider than the width it declares. + +use crate::context::LintContext; +use crate::literal; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::token::TokenKind; + +/// See [`Rule::doc`]. +pub struct TruncatedNumericLiteral; + +const NAME: &str = "truncated-numeric-literal"; + +impl Rule for TruncatedNumericLiteral { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "keep a sized literal inside the width it declares" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "`4'hFFF` is not an error and not a warning in most simulators: the \ + value is silently truncated to `4'hF` and the extra digits are gone. \ + Whichever half of it was wrong — the width or the value — the code \ + does not do what it reads as, and the reader has to count nibbles to \ + see it. Verible's `truncated-numeric-literal` (\"Checks that numeric \ + literals are not longer than their stated bit-width to avoid \ + undesired accidental truncation.\", enabled by default) is the same \ + rule. Leading zeros do not count (`8'h0FF` is eight bits), an `x` or \ + `z` digit counts as a full digit, and a decimal literal carrying `x` \ + is not judged at all. A literal whose digits are **all** unknown \ + (`3'hz`, `7'hzz`) is left alone: those are how the language spells a \ + three-bit and a seven-bit `z`, and their digit count only exceeds the \ + width because a hex digit is four bits. No automatic fix: only the \ + author knows which of the two numbers was meant." + } + + fn check(&self, ctx: &LintContext) -> Vec { + ctx.tokens() + .iter() + .filter(|token| token.kind == TokenKind::Number) + .filter_map(|token| { + let parsed = literal::parse(&token.text)?; + let bits = parsed.significant_bits()?; + if bits <= parsed.width || all_unknown(&parsed.packed_digits()) { + return None; + } + Some(Violation::new( + NAME, + format!( + "literal needs {bits} bits but declares {}; the value is truncated", + parsed.width + ), + token.span, + )) + }) + .collect() + } +} + +/// True when every digit is `x`, `z` or `?`. +/// +/// `3'hz` and `7'hzz` are how the language spells a three-bit and a seven-bit +/// `z`: the digit count exceeds the width by construction, because one hex +/// digit is four bits, and nothing is being truncated — the value is unknown +/// either way. Measured on opentitan, this shape was every one of the rule's +/// findings in `top_earlgrey/dv/tb/tb.sv`. +fn all_unknown(digits: &str) -> bool { + !digits.is_empty() && digits.chars().all(|c| matches!(c.to_ascii_lowercase(), 'x' | 'z' | '?')) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + TruncatedNumericLiteral.check(&LintContext::new(src, None)) + } + + fn assign(value: &str) -> String { + format!("module m;\n assign x = {value};\nendmodule\n") + } + + #[test] + fn flags_a_literal_that_does_not_fit() { + let found = violations(&assign("4'hFFF")); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("12 bits"), "{}", found[0].message); + assert!(found[0].message.contains("declares 4"), "{}", found[0].message); + assert!(found[0].fix.is_none()); + } + + #[test] + fn flags_every_base() { + for value in ["1'b11", "2'o77", "4'hFF", "4'd16", "8'd300"] { + assert_eq!(violations(&assign(value)).len(), 1, "{value}"); + } + } + + #[test] + fn a_literal_that_fits_is_silent() { + for value in [ + "4'hF", + "4'h0F", + "8'h0FF", + "8'b0000_0001", + "32'hdead_beef", + "8'd255", + "4'h0", + "1'b0", + "8'sh7f", + ] { + assert!( + violations(&assign(value)).is_empty(), + "{value}: {:?}", + violations(&assign(value)) + ); + } + } + + #[test] + fn an_unknown_digit_counts_but_a_decimal_unknown_is_not_judged() { + assert_eq!(violations(&assign("4'hxF")).len(), 1, "two nibbles in a one-nibble literal"); + assert!(violations(&assign("4'hx")).is_empty(), "one nibble fits"); + assert!(violations(&assign("8'dx")).is_empty(), "a decimal x says nothing about width"); + } + + /// `3'hz` is a three-bit `z`, not a truncated four-bit one — the shape + /// that was every opentitan finding in `top_earlgrey/dv/tb/tb.sv`. + #[test] + fn an_all_unknown_literal_is_not_truncated() { + for value in ["3'hz", "7'hzz", "1'bx", "5'h??", "3'hZ"] { + assert!( + violations(&assign(value)).is_empty(), + "{value}: {:?}", + violations(&assign(value)) + ); + } + // A mixed literal still counts its digits. + assert_eq!(violations(&assign("4'hxF")).len(), 1); + } + + #[test] + fn an_unsized_literal_and_a_plain_number_are_not_judged() { + for value in ["'h1f", "42", "1.5", "'0", "'1"] { + assert!(violations(&assign(value)).is_empty(), "{value}"); + } + } +} diff --git a/crates/vlog_linter/src/rules/undeclared_identifier.rs b/crates/vlog_linter/src/rules/undeclared_identifier.rs new file mode 100644 index 0000000..7c586cb --- /dev/null +++ b/crates/vlog_linter/src/rules/undeclared_identifier.rs @@ -0,0 +1,238 @@ +//! `undeclared-identifier` — a name nothing in the project declares. + +use std::collections::BTreeSet; + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::ast::ItemKind; +use vlog_semantic::{words, Resolution}; + +/// See [`Rule::doc`]. +pub struct UndeclaredIdentifier; + +const NAME: &str = "undeclared-identifier"; + +impl Rule for UndeclaredIdentifier { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "use a name something declares" + } + + fn severity(&self) -> Severity { + Severity::Error + } + + fn doc(&self) -> &'static str { + "A misspelled signal name is the one mistake in Verilog that costs \ + nothing to make and hours to find: an undeclared identifier in a \ + value position is an elaboration error in a strict tool and an \ + implicit one-bit net in a permissive one, and the second is worse — \ + the design builds, the bit stays `z`, and the bug surfaces in \ + simulation as a value nobody can trace. This rule reports a name that \ + **this file** does not declare, that no external unit it names could \ + supply, and that **no other file in the project writes down at all**.\n\n\ + Every one of those clauses is an exclusion, and they are what make an \ + Error-class rule about names safe to run. It says nothing at all \ + unless the run can see the project (`lucisv check `, or the \ + language server), because the whole case for a finding is that the \ + name appears nowhere else. It says nothing about a name any macro \ + invocation, compiler directive or attribute in this file writes down \ + — text lucisv never expands, and where half the identifiers in a \ + testbench live. It says nothing about a file that did not fully \ + parse, where error recovery moves declarations between scopes. And it \ + says nothing where the single-file analysis already knew it could not \ + answer: a package member, an inherited name, a hierarchical tail and \ + a `.port` connection all resolve elsewhere and never reach here. \ + Verible has no equivalent rule — its linter is syntax-only.\n\n\ + **Measured before it was switched on.** Over opentitan's `hw/` \ + (3 975 files) and over lucisv's own 860-file corpus it reports the \ + same five findings, in one file: `ibex/dv/formal/spec/spec_api.sv` \ + connects `.mhartid_out(mhart_id_o)` and four siblings to names its \ + module header never declares, which is exactly the implicit net this \ + rule exists to find. No false positive survived the exclusions, so it \ + ships on wherever there is a project — the same terms `unused-signal` \ + and `undriven-net` run on. No automatic fix: a misspelling has no one \ + repair." + } + + fn default_on(&self) -> bool { + false + } + + fn needs_workspace(&self) -> bool { + true + } + + fn check(&self, ctx: &LintContext) -> Vec { + // The whole case for a finding is "nothing else in the project writes + // this name down", which a run that cannot see the project cannot + // make. Without an oracle this rule has nothing to say — and saying + // it anyway would accuse every name in every buffer. + if !ctx.has_oracle() || !ctx.parsed_cleanly() || !declares_a_unit(ctx) { + return Vec::new(); + } + let raw: BTreeSet = words::harvest_raw(ctx.tokens()).into_iter().collect(); + let semantics = ctx.semantics(); + semantics + .references() + .iter() + .filter(|reference| reference.resolution == Resolution::NotFound) + .filter(|reference| !reference.name_span.is_empty()) + // A use written at **file scope** belongs to no unit; the + // fragment guard above has already dropped the files where that + // is the whole file, and what is left is a stray. + .filter(|reference| reference.scope != semantics.file_scope()) + // A name the file declares *somewhere* — a generate block's + // label reached through a hierarchical path, a member of a scope + // this use is not written in — is a name that exists; whether the + // path to it is right is more than this rule claims to know. + .filter(|reference| semantics.symbols_named(&reference.name).next().is_none()) + .filter(|reference| !raw.contains(&reference.name)) + .filter(|reference| !ctx.mentioned_elsewhere(&reference.name)) + .map(|reference| { + Violation::new( + NAME, + format!("`{}` is declared nowhere in the project", reference.name), + reference.name_span, + ) + }) + .collect() + } +} + +/// True when the file declares a design unit of its own — a module, an +/// interface, a program, a package or a class. +/// +/// A file that declares none but still holds declarations and assignments is +/// a **fragment**: the middle of a module body, written to be `` `include``d +/// at that point (`docs/features/fragment-mode/README.md`), where every name +/// it reads is declared by the file that includes it and no census of *this* +/// file can see them. Measured on opentitan: every one of the rule's 94 +/// findings was in four such fragments in ibex's formal harness plus one +/// generate label, and this guard plus the declared-here guard removes all +/// of them. +fn declares_a_unit(ctx: &LintContext) -> bool { + let mut found = false; + crate::visit::walk_items(ctx.file(), &mut |item| { + found |= matches!( + item.kind, + ItemKind::Module(_) | ItemKind::Package { .. } | ItemKind::Class(_) + ); + }); + found +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::MentionOracle; + + /// A project in which these names are written down somewhere else. + struct Elsewhere(&'static [&'static str]); + + impl MentionOracle for Elsewhere { + fn mentioned_elsewhere(&self, name: &str) -> bool { + self.0.contains(&name) + } + } + + fn violations(src: &str, elsewhere: &'static [&'static str]) -> Vec { + let ctx = LintContext::new(src, None); + let oracle = Elsewhere(elsewhere); + UndeclaredIdentifier.check(&ctx.with_oracle(&oracle)) + } + + #[test] + fn flags_a_name_nothing_declares_and_nothing_else_mentions() { + let src = "module m;\n logic data;\n assign x = dara;\nendmodule\n"; + let found = violations(src, &[]); + assert!(found.iter().any(|v| v.message.contains("`dara`")), "{found:?}"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_declared_name_is_never_flagged() { + let src = "module m;\n logic data;\n assign data = 1'b0;\nendmodule\n"; + assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[])); + } + + /// The rule's whole safety net: a name some other file writes down — + /// however it writes it — is not an accusation this rule will make. + #[test] + fn a_name_another_file_mentions_is_left_alone() { + let src = "module m;\n assign x = elsewhere_sig;\nendmodule\n"; + assert!(violations(src, &["elsewhere_sig", "x"]).is_empty()); + } + + #[test] + fn a_name_this_files_macro_text_writes_down_is_left_alone() { + // `MY_SIG` is produced by a macro lucisv never expands; the census of + // raw text is what tells the rule to keep quiet. + let src = "module m;\n\ + logic x;\n\ + `define MY_SIG some_sig\n\ + assign x = some_sig;\n\ + endmodule\n"; + assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[])); + } + + /// An `` `include``d fragment — a module body with no module around it — + /// reads names the including file declares, and no census of this file + /// can see them. It was 85 of the 94 opentitan findings. + #[test] + fn an_include_fragment_gets_no_opinion() { + let src = "assign pre_pc = other_sig;\nlogic [3:0] pre_regs;\n"; + assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[])); + } + + /// A generate label reached through a hierarchical path is declared in + /// this file, just not in the scope the use is written in. + #[test] + fn a_name_this_file_declares_somewhere_is_left_alone() { + let src = "module m;\n\ + if (1) begin : gen_lfsr\n\ + logic state_q;\n\ + end\n\ + assign x = gen_lfsr;\n\ + endmodule\n"; + let found = violations(src, &[]); + assert!(!found.iter().any(|v| v.message.contains("gen_lfsr")), "{found:?}"); + } + + #[test] + fn a_run_with_no_project_behind_it_says_nothing() { + let src = "module m;\n assign x = dara;\nendmodule\n"; + let ctx = LintContext::new(src, None); + assert!(UndeclaredIdentifier.check(&ctx).is_empty(), "no oracle, no opinion"); + } + + #[test] + fn a_file_that_did_not_parse_gets_no_opinion() { + let src = "module m;\n @@@ junk\n assign x = dara;\nendmodule\n"; + assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[])); + } + + #[test] + fn a_package_member_and_a_hierarchical_tail_never_reach_this_rule() { + // Both resolve somewhere else — an external candidate or a member — + // so neither is a `NotFound`, which is what this rule reports. + for src in [ + "module m;\n assign x = pkg::thing;\nendmodule\n", + "module m;\n assign x = tb.dut.sig;\nendmodule\n", + "module m;\n import p::*;\n assign x = from_pkg;\nendmodule\n", + ] { + let found = violations(src, &[]); + assert!( + !found.iter().any(|v| v.message.contains("thing") + || v.message.contains("sig") + || v.message.contains("from_pkg")), + "{src}: {found:?}" + ); + } + } +} diff --git a/crates/vlog_linter/src/rules/undersized_binary_literal.rs b/crates/vlog_linter/src/rules/undersized_binary_literal.rs new file mode 100644 index 0000000..59e9258 --- /dev/null +++ b/crates/vlog_linter/src/rules/undersized_binary_literal.rs @@ -0,0 +1,187 @@ +//! `undersized-binary-literal` — write every bit of a sized binary literal. + +use crate::context::LintContext; +use crate::literal; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::{Applicability, Fix, Violation}; +use vlog_parser::span::TextRange; +use vlog_parser::token::TokenKind; + +/// See [`Rule::doc`]. +pub struct UndersizedBinaryLiteral; + +const NAME: &str = "undersized-binary-literal"; + +impl Rule for UndersizedBinaryLiteral { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "write every bit of a sized binary literal" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "`8'b1` is one bit written where eight were declared, and a reader has \ + to remember the zero-extension rule to know it is `8'b0000_0001` — \ + while the very similar `8'bx` is *not* `8'b0000_000x` but eight `x`s, \ + because a leading `x` or `z` extends instead of zero-filling. Spelling \ + every bit takes the rule out of the reader's head. Verible's \ + `undersized-binary-literal` (\"Checks that the digits of binary \ + literals for the configured bases match their declared width.\", \ + enabled by default, binary only by default) is the same rule and the \ + same default; lucisv checks binary alone for the same reason, and — \ + also following that rule's defaults, whose `lint_zero` option is \ + off — leaves a literal whose value is **zero** alone: `2'b0` is not \ + a truncation waiting to happen, it is how the language spells zero. \ + The fix \ + is **safe**: it writes the extension the language would have applied, \ + which is `0` for a literal starting with `0` or `1` and the unknown \ + itself for one starting with `x` or `z`. Underscore separators are \ + preserved as written, and a literal *wider* than its declaration is \ + `truncated-numeric-literal`'s business, not this one's." + } + + fn fix(&self) -> Option { + Some(Applicability::Safe) + } + + fn check(&self, ctx: &LintContext) -> Vec { + ctx.tokens() + .iter() + .filter(|token| token.kind == TokenKind::Number) + .filter_map(|token| { + let parsed = literal::parse(&token.text)?; + if parsed.base != 'b' { + return None; + } + let digits = parsed.packed_digits(); + let written = digits.chars().count() as u32; + if written >= parsed.width || is_zero(&digits) { + return None; + } + let padding = pad_char(&digits)?; + let missing = (parsed.width - written) as usize; + // The pad goes in front of the first digit as written, so an + // `_` the author put in the middle stays where it was. + let first = token.span.end - parsed.digits.len() as u32; + Some( + Violation::new( + NAME, + format!("binary literal writes {written} of its {} bits", parsed.width), + token.span, + ) + .with_fix(Fix::safe(vec![( + TextRange::new(first, first), + padding.to_string().repeat(missing), + )])), + ) + }) + .collect() + } +} + +/// True for a literal whose written value is zero — `1'b0`, `8'b0`, `4'b00`. +/// +/// Exempt because Verible's `lint_zero` option defaults to **false**, and +/// matching its default is what keeps a Verible-clean codebase lucisv-clean: +/// measured on opentitan, `'b0` accounts for the great majority of every +/// undersized binary literal in the tree, and every one of them reads exactly +/// as it means. +fn is_zero(digits: &str) -> bool { + digits.chars().all(|c| c == '0') +} + +/// The digit the language would extend this literal with: an unknown extends +/// itself, everything else extends with `0` (IEEE 1800 §5.7.1). `None` for an +/// empty digit run, which [`literal::parse`] never produces. +fn pad_char(digits: &str) -> Option { + match digits.chars().next()?.to_ascii_lowercase() { + c @ ('x' | 'z' | '?') => Some(c), + _ => Some('0'), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::violation::apply_fixes; + + fn violations(src: &str) -> Vec { + UndersizedBinaryLiteral.check(&LintContext::new(src, None)) + } + + fn assign(value: &str) -> String { + format!("module m;\n assign x = {value};\nendmodule\n") + } + + fn fixed(value: &str) -> String { + let src = assign(value); + apply_fixes(&src, &violations(&src), false).output + } + + #[test] + fn flags_a_short_binary_literal_and_pads_it() { + let src = assign("8'b1"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("1 of its 8"), "{}", found[0].message); + assert_eq!(fixed("8'b1"), assign("8'b00000001")); + } + + #[test] + fn an_unknown_extends_itself_not_with_zeros() { + assert_eq!(fixed("4'bx"), assign("4'bxxxx")); + assert_eq!(fixed("4'bz"), assign("4'bzzzz")); + // ... and a literal that only *contains* an unknown still zero-fills, + // because the language looks at the leftmost digit. + assert_eq!(fixed("4'b1x"), assign("4'b001x")); + } + + #[test] + fn separators_stay_where_the_author_put_them() { + assert_eq!(fixed("8'b1_1"), assign("8'b0000001_1")); + } + + /// Verible's `lint_zero` defaults to off, and so does lucisv: `2'b0` was + /// the great majority of this rule's opentitan findings before the exempt. + #[test] + fn a_zero_literal_is_exempt() { + for value in ["2'b0", "8'b0", "4'b00", "1'b0", "32'b0_0"] { + assert!(violations(&assign(value)).is_empty(), "{value}"); + } + // A non-zero literal of the same width is still reported. + assert_eq!(violations(&assign("2'b1")).len(), 1); + } + + #[test] + fn a_full_width_literal_is_silent() { + for value in ["8'b0000_0001", "1'b0", "4'b1010", "4'bxxxx"] { + assert!(violations(&assign(value)).is_empty(), "{value}"); + } + } + + #[test] + fn only_binary_is_judged_and_only_when_sized() { + for value in ["8'h1", "8'd1", "8'o1", "'b1", "42"] { + assert!(violations(&assign(value)).is_empty(), "{value}"); + } + } + + #[test] + fn an_oversized_literal_belongs_to_the_other_rule() { + assert!(violations(&assign("1'b11")).is_empty()); + } + + #[test] + fn the_fix_leaves_the_file_clean() { + let src = assign("8'b1"); + let once = apply_fixes(&src, &violations(&src), false).output; + assert!(violations(&once).is_empty(), "idempotent: {once}"); + } +} diff --git a/crates/vlog_linter/src/rules/undriven_net.rs b/crates/vlog_linter/src/rules/undriven_net.rs index 30448cf..e39889e 100644 --- a/crates/vlog_linter/src/rules/undriven_net.rs +++ b/crates/vlog_linter/src/rules/undriven_net.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::signals::intentionally_unused; use crate::violation::Violation; @@ -19,6 +20,10 @@ impl Rule for UndrivenNet { "drive a signal that something reads" } + fn severity(&self) -> Severity { + Severity::Warning + } + fn doc(&self) -> &'static str { "A net read by the design but assigned by nothing is `z` forever, and \ a variable in the same position is `x` forever. In simulation this \ diff --git a/crates/vlog_linter/src/rules/unknown_parameter.rs b/crates/vlog_linter/src/rules/unknown_parameter.rs new file mode 100644 index 0000000..c7ef53c --- /dev/null +++ b/crates/vlog_linter/src/rules/unknown_parameter.rs @@ -0,0 +1,145 @@ +//! `unknown-parameter` — a `#(.NAME(…))` the module does not declare. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_instantiations; + +/// See [`Rule::doc`]. +pub struct UnknownParameter; + +const NAME: &str = "unknown-parameter"; + +impl Rule for UnknownParameter { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "override only parameters the instantiated module declares" + } + + fn severity(&self) -> Severity { + Severity::Error + } + + fn doc(&self) -> &'static str { + "`#(.Width(8))` on a module whose parameter is called `DataWidth` is \ + an elaboration error, and — worse than the port version — the \ + *silent* failure mode is real: a tool that accepts the override \ + anyway elaborates the module at its declared default, so the design \ + builds and is the wrong width. A `localparam` is not overridable at \ + all (IEEE 1800 §6.20.4), so naming one here is the same error wearing \ + a different hat, and lucisv reports it: the parameter list this rule \ + checks against holds every `parameter` of the header and the body and \ + no `localparam` of either. Verible has no equivalent; this is TODO \ + §33.2's own rule.\n\n\ + It keeps `unknown-port`'s silences exactly: no project, an unindexed \ + module, one declared twice with different headers, one whose header \ + carries a compiler directive, and a scope-qualified instantiation are \ + all cases where the run cannot answer and the rule says nothing. A \ + positional override names nothing to check — that is `module-\ + parameter`'s subject. No automatic fix." + } + + fn default_on(&self) -> bool { + // Off without a project: with no interface table to ask, every named + // override would be unanswerable and the rule would be a no-op that + // still cost a walk. + false + } + + fn needs_workspace(&self) -> bool { + true + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_instantiations(ctx.file(), &mut |inst| { + if inst.module.contains(':') { + return; + } + let Some(params) = &inst.params else { return }; + let Some(interface) = ctx.module_interface(&inst.module) else { return }; + for param in params { + if param.name == "*" || param.name_span.is_empty() { + continue; + } + if interface.has_parameter(¶m.name) { + continue; + } + out.push(Violation::new( + NAME, + format!("`{}` declares no overridable parameter `{}`", inst.module, param.name), + param.name_span, + )); + } + }); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::context::{MentionOracle, ModuleInterface}; + + /// A project holding one module with these overridable parameters. + struct Project(&'static str, &'static [&'static str]); + + impl MentionOracle for Project { + fn mentioned_elsewhere(&self, _name: &str) -> bool { + false + } + + fn module_interface(&self, name: &str) -> Option { + (name == self.0).then(|| ModuleInterface { + ports: Vec::new(), + parameters: self.1.iter().map(|p| p.to_string()).collect(), + }) + } + } + + fn violations(src: &str, project: &'static Project) -> Vec { + let ctx = LintContext::new(src, None); + UnknownParameter.check(&ctx.with_oracle(project)) + } + + static SUB: Project = Project("sub", &["Width", "Depth"]); + + #[test] + fn flags_an_override_the_module_does_not_declare() { + let src = "module m;\n sub #(.Width(8), .Deth(4)) u ();\nendmodule\n"; + let found = violations(src, &SUB); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`Deth`"), "{}", found[0].message); + assert_eq!(&src[found[0].span.as_range()], "Deth"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_declared_parameter_is_never_flagged() { + let src = "module m;\n sub #(.Width(8), .Depth(4)) u ();\nendmodule\n"; + assert!(violations(src, &SUB).is_empty(), "{:?}", violations(src, &SUB)); + } + + #[test] + fn a_positional_override_names_nothing_to_check() { + assert!(violations("module m;\n sub #(8, 4) u ();\nendmodule\n", &SUB).is_empty()); + assert!(violations("module m;\n sub u ();\nendmodule\n", &SUB).is_empty()); + } + + #[test] + fn an_unindexed_module_and_a_run_with_no_project_are_both_silent() { + assert!(violations("module m;\n other #(.Nope(1)) u ();\nendmodule\n", &SUB).is_empty()); + let src = "module m;\n sub #(.Nope(1)) u ();\nendmodule\n"; + assert!(UnknownParameter.check(&LintContext::new(src, None)).is_empty()); + } + + #[test] + fn a_scope_qualified_instantiation_is_left_to_the_workspace() { + let src = "module m;\n pkg::sub #(.Nope(1)) u ();\nendmodule\n"; + assert!(violations(src, &SUB).is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/unknown_port.rs b/crates/vlog_linter/src/rules/unknown_port.rs new file mode 100644 index 0000000..1f0bfeb --- /dev/null +++ b/crates/vlog_linter/src/rules/unknown_port.rs @@ -0,0 +1,169 @@ +//! `unknown-port` — a `.name(…)` the instantiated module does not declare. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_instantiations; +use vlog_parser::ast::Connections; + +/// See [`Rule::doc`]. +pub struct UnknownPort; + +const NAME: &str = "unknown-port"; + +impl Rule for UnknownPort { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "connect only ports the instantiated module declares" + } + + fn severity(&self) -> Severity { + Severity::Error + } + + fn doc(&self) -> &'static str { + "`.data_i(x)` on a module that declares `data_in` is an elaboration \ + error in every tool, and the commonest way to reach it is a port \ + rename that reached the declaration and three of its four \ + instantiations. The fourth is in another file, so nothing about the \ + file being edited says anything is wrong. Verible has no equivalent \ + — its linter reads one file at a time — and this is TODO §33.2's own \ + rule.\n\n\ + **Silent whenever the project cannot answer**, which is what an \ + Error-class rule owes: with no project behind the run at all, for a \ + module the project does not declare, for one declared more than once \ + with different headers, and for one whose header lucisv cannot read \ + whole — a port list carrying a compiler directive is the case that \ + matters, because a macro standing where a port belongs expands to \ + names lucisv never sees. A `.*` connection names nothing and is not \ + judged, and a scope-qualified instantiation (`pkg::mod`) is left to \ + the workspace. No automatic fix: the right port name is a guess, and \ + a wrong guess here rewires a design." + } + + fn default_on(&self) -> bool { + // Off without a project: with no interface table to ask, every named + // connection would be unanswerable and the rule would be a no-op that + // still cost a walk. + false + } + + fn needs_workspace(&self) -> bool { + true + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_instantiations(ctx.file(), &mut |inst| { + if inst.module.contains(':') { + return; + } + let Some(interface) = ctx.module_interface(&inst.module) else { return }; + for instance in &inst.instances { + let Connections::Named(conns) = &instance.conns else { continue }; + for conn in conns { + if conn.name == "*" || conn.name_span.is_empty() { + continue; + } + if interface.has_port(&conn.name) { + continue; + } + out.push(Violation::new( + NAME, + format!("`{}` declares no port `{}`", inst.module, conn.name), + conn.name_span, + )); + } + } + }); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::context::{MentionOracle, ModuleInterface}; + + /// A project holding one module with these ports. + struct Project(&'static str, &'static [&'static str]); + + impl MentionOracle for Project { + fn mentioned_elsewhere(&self, _name: &str) -> bool { + false + } + + fn module_interface(&self, name: &str) -> Option { + (name == self.0).then(|| ModuleInterface { + ports: self.1.iter().map(|p| p.to_string()).collect(), + parameters: Vec::new(), + }) + } + } + + fn violations(src: &str, project: &'static Project) -> Vec { + let ctx = LintContext::new(src, None); + UnknownPort.check(&ctx.with_oracle(project)) + } + + static SUB: Project = Project("sub", &["clk_i", "data_i"]); + + #[test] + fn flags_a_connection_the_module_does_not_declare() { + let src = "module m;\n sub u (.clk_i(clk), .dara_i(d));\nendmodule\n"; + let found = violations(src, &SUB); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`dara_i`"), "{}", found[0].message); + assert_eq!(&src[found[0].span.as_range()], "dara_i"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_declared_port_is_never_flagged() { + let src = "module m;\n sub u (.clk_i(clk), .data_i(d));\nendmodule\n"; + assert!(violations(src, &SUB).is_empty(), "{:?}", violations(src, &SUB)); + } + + #[test] + fn a_module_the_project_does_not_declare_is_left_alone() { + let src = "module m;\n other u (.whatever(x));\nendmodule\n"; + assert!(violations(src, &SUB).is_empty()); + } + + #[test] + fn a_wildcard_and_a_positional_list_name_nothing_to_check() { + assert!(violations("module m;\n sub u (.*);\nendmodule\n", &SUB).is_empty()); + assert!(violations("module m;\n sub u (a, b);\nendmodule\n", &SUB).is_empty()); + } + + #[test] + fn a_run_with_no_project_says_nothing() { + let src = "module m;\n sub u (.dara_i(d));\nendmodule\n"; + assert!(UnknownPort.check(&LintContext::new(src, None)).is_empty()); + } + + #[test] + fn a_scope_qualified_instantiation_is_left_to_the_workspace() { + let src = "module m;\n pkg::sub u (.dara_i(d));\nendmodule\n"; + assert!(violations(src, &SUB).is_empty()); + } + + #[test] + fn an_implicit_named_connection_is_judged_too() { + // `.clk_i` with no parentheses is a named connection like any other. + let src = "module m;\n sub u (.clk_i, .dara_i);\nendmodule\n"; + let found = violations(src, &SUB); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("`dara_i`"), "{}", found[0].message); + } + + #[test] + fn every_instance_of_one_statement_is_judged() { + let src = "module m;\n sub u1 (.dara_i(a)), u2 (.data_i(b));\nendmodule\n"; + assert_eq!(violations(src, &SUB).len(), 1); + } +} diff --git a/crates/vlog_linter/src/rules/unused_signal.rs b/crates/vlog_linter/src/rules/unused_signal.rs index d570a21..66d0be0 100644 --- a/crates/vlog_linter/src/rules/unused_signal.rs +++ b/crates/vlog_linter/src/rules/unused_signal.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::signals::intentionally_unused; use crate::violation::Violation; @@ -19,6 +20,10 @@ impl Rule for UnusedSignal { "delete a signal nothing uses" } + fn severity(&self) -> Severity { + Severity::Warning + } + fn doc(&self) -> &'static str { "A `wire` or `logic` that nothing reads and nothing drives is dead \ weight: it costs a reader the effort of working out what it is for, \ diff --git a/crates/vlog_linter/src/rules/unused_waiver.rs b/crates/vlog_linter/src/rules/unused_waiver.rs index 9cb89c9..601c58f 100644 --- a/crates/vlog_linter/src/rules/unused_waiver.rs +++ b/crates/vlog_linter/src/rules/unused_waiver.rs @@ -2,6 +2,7 @@ use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use crate::waiver::UNUSED_WAIVER; @@ -17,6 +18,10 @@ impl Rule for UnusedWaiver { "remove waivers that no longer suppress anything" } + fn severity(&self) -> Severity { + Severity::Style + } + fn doc(&self) -> &'static str { "A `// lucisv: waive` comment outlives the problem it was written for: \ the code is fixed, the waiver stays, and the next reader believes the \ diff --git a/crates/vlog_linter/src/rules/void_cast.rs b/crates/vlog_linter/src/rules/void_cast.rs new file mode 100644 index 0000000..f728049 --- /dev/null +++ b/crates/vlog_linter/src/rules/void_cast.rs @@ -0,0 +1,151 @@ +//! `void-cast` — `void'(…)` around something that is not a call. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_all_stmts; +use vlog_parser::ast::{Expr, ExprKind, StmtKind}; + +/// See [`Rule::doc`]. +pub struct VoidCast; + +const NAME: &str = "void-cast"; + +impl Rule for VoidCast { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "cast to `void` only what a call returns" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "`void'(expr)` exists for exactly one purpose: calling a function for \ + its side effect and saying out loud that the return value is being \ + thrown away (IEEE 1800 §13.4.1). Around anything that is not a call — \ + a variable, a literal, an arithmetic expression — it discards a value \ + nobody computed for a side effect, which means either the call that \ + was meant to be there is missing or the cast is left over from an \ + edit. Verible ships a `void-cast` rule (\"Checks that void casts do \ + not contain certain function/method calls.\", enabled by default) \ + with a different subject: **it forbids a named list of calls** whose \ + result must be checked (`randomize`, `uvm_hdl_read`). lucisv's is the \ + complementary check TODO §33 asked for — the operand must be a call \ + at all — and takes no list, so the two do not overlap and neither \ + replaces the other; the named-call form belongs with the per-rule \ + options of wave 2. No automatic fix: whether the repair is to delete \ + the cast or to add the missing call is the author's to decide.\n\n\ + Only a `void'(...)` standing **as a statement** is judged, which is \ + the one place the construct belongs: a `void` value gives an \ + enclosing expression nothing to do with it, so a `void'` buried in an \ + rvalue is a different mistake and one this rule stays out of." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_all_stmts(ctx.file(), &mut |stmt| { + let StmtKind::ExprStmt(expr) = &stmt.kind else { return }; + let ExprKind::Cast { ty, expr: inner, pattern, .. } = &expr.kind else { return }; + if *pattern || !is_void(ty) || is_call(inner) { + return; + } + out.push(Violation::new( + NAME, + "`void'(...)` around something that is not a call; nothing is being discarded", + expr.span, + )); + }); + out + } +} + +/// True for the casting type `void`, however it is spelled in the tree. +fn is_void(ty: &Expr) -> bool { + matches!(&ty.kind, ExprKind::Ident(name) if name == "void") + || matches!(&ty.kind, ExprKind::Type(data) if data.name == "void") +} + +/// True when the cast's operand is a call — the only thing `void'` is for. +/// +/// A method call reaches here as a `Call` whose callee is a `Member` +/// (`obj.randomize()`), and a `new` expression is a constructor call; both +/// count, and so does a call carrying a `with` clause — `void'(randomize(x) +/// with { … })` is the commonest void cast there is. A parenthesized operand +/// is looked through, because `void'((f()))` is the same statement written +/// twice. +fn is_call(expr: &Expr) -> bool { + match &expr.kind { + ExprKind::Call { .. } | ExprKind::New(_) => true, + ExprKind::Paren { inner, .. } => is_call(inner), + ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => is_call(base), + // A cast around a cast is somebody being explicit about a return + // type; look through it rather than accuse the outer one. + ExprKind::Cast { expr: inner, .. } => is_call(inner), + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + VoidCast.check(&LintContext::new(src, None)) + } + + fn stmt(text: &str) -> String { + format!("module m;\n initial begin\n {text}\n end\nendmodule\n") + } + + #[test] + fn flags_a_void_cast_of_a_plain_value() { + let src = stmt("void'(x);"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "void'(x)"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_call_is_what_a_void_cast_is_for() { + for text in [ + "void'(f());", + "void'(obj.randomize());", + "void'(pkg::f(1, 2));", + "void'(q.pop_front());", + "void'((f()));", + "void'($cast(a, b));", + "void'(randomize(x) with { x inside {[0:7]}; });", + "void'(q.sum() with (item.w));", + ] { + assert!(violations(&stmt(text)).is_empty(), "{text}: {:?}", violations(&stmt(text))); + } + } + + #[test] + fn a_cast_to_something_else_is_not_this_rules_business() { + for text in ["a = int'(x);", "a = logic'(x);", "a = my_t'(x);", "a = 4'(x);"] { + assert!(violations(&stmt(text)).is_empty(), "{text}"); + } + } + + #[test] + fn only_a_statement_position_cast_is_judged() { + // A `void'` in an rvalue is a different mistake; this rule is about + // the statement idiom and says nothing there. + assert!(violations(&stmt("a = void'(x);")).is_empty()); + } + + #[test] + fn a_non_call_operand_of_any_shape_is_flagged() { + for text in ["void'(1);", "void'(a + b);", "void'(s.field);", "void'(q[0]);"] { + assert_eq!(violations(&stmt(text)).len(), 1, "{text}"); + } + } +} diff --git a/crates/vlog_linter/src/rules/wire_reg_mixup.rs b/crates/vlog_linter/src/rules/wire_reg_mixup.rs index 296c269..3d15b63 100644 --- a/crates/vlog_linter/src/rules/wire_reg_mixup.rs +++ b/crates/vlog_linter/src/rules/wire_reg_mixup.rs @@ -4,6 +4,7 @@ use std::path::Path; use crate::context::LintContext; use crate::registry::Rule; +use crate::severity::Severity; use crate::violation::Violation; use vlog_parser::token::TokenKind; @@ -21,6 +22,10 @@ impl Rule for WireRegMixup { "use `logic` instead of `reg` in SystemVerilog files" } + fn severity(&self) -> Severity { + Severity::Error + } + fn doc(&self) -> &'static str { "`reg` is Verilog-1995's name for a variable, and its worst property is \ that it reads like hardware: generations of engineers have written \ diff --git a/crates/vlog_linter/src/severity.rs b/crates/vlog_linter/src/severity.rs new file mode 100644 index 0000000..5bd4750 --- /dev/null +++ b/crates/vlog_linter/src/severity.rs @@ -0,0 +1,82 @@ +//! How bad a finding is: the three classes every rule states. +//! +//! Verible has no such notion — every one of its rules produces the same +//! diagnostic — and ruff spells it as a rule *prefix* (`E`, `W`, `F`). lucisv +//! takes ruff's idea and Verible's vocabulary: three words a user can select, +//! ignore and toggle by, chosen so the question they answer is "would a tool +//! refuse this file?" rather than "how annoyed am I". + +/// How bad one rule's findings are. +/// +/// The order is worst-first, and it is the order a generated document and a +/// settings UI list the classes in — so [`Ord`] is derived rather than +/// hand-written, and sorting by it sorts by seriousness. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Severity { + /// The code would very likely fail to compile, elaborate or synthesize. + /// A rule may only claim this when it is certain: an `Error` finding is an + /// accusation, so every rule in this class stays silent whenever it cannot + /// answer — see `docs/features/linter-expansion-1/README.md`. + Error, + /// The code compiles, and means something the author probably did not + /// intend: a latch where none was wanted, a deprecated construct, a + /// literal that does not fit its width. + Warning, + /// The code is correct and reads badly: naming, tabs, a redundant `;`. + Style, +} + +impl Severity { + /// Every class, worst first — the order rules and settings are grouped in. + pub const ALL: [Severity; 3] = [Severity::Error, Severity::Warning, Severity::Style]; + + /// The word this class is spelled with everywhere a user meets it: + /// `--select`, `--ignore`, the CLI diagnostic line, the JSON output and + /// the generated rule reference. + pub fn as_str(self) -> &'static str { + match self { + Severity::Error => "error", + Severity::Warning => "warning", + Severity::Style => "style", + } + } + + /// The class that word names, or `None` when it names no class. + pub fn from_name(name: &str) -> Option { + Severity::ALL.into_iter().find(|severity| severity.as_str() == name) + } + + /// One line saying what the class means, for the generated reference and + /// for the settings UI — one wording, so the two cannot drift. + pub fn describes(self) -> &'static str { + match self { + Severity::Error => { + "code that would very likely fail to compile, elaborate or synthesize" + } + Severity::Warning => "code that compiles but very likely does not mean what it says", + Severity::Style => "code that is correct and reads badly", + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_class_round_trips_through_its_word() { + for severity in Severity::ALL { + assert_eq!(Severity::from_name(severity.as_str()), Some(severity)); + assert!(!severity.describes().is_empty()); + } + assert_eq!(Severity::from_name("errors"), None); + assert_eq!(Severity::from_name("Error"), None, "matched exactly, like every other name"); + } + + #[test] + fn the_classes_are_ordered_worst_first() { + let mut shuffled = [Severity::Style, Severity::Error, Severity::Warning]; + shuffled.sort_unstable(); + assert_eq!(shuffled, Severity::ALL); + } +} diff --git a/crates/vlog_linter/src/violation.rs b/crates/vlog_linter/src/violation.rs index b4f9848..903b4d9 100644 --- a/crates/vlog_linter/src/violation.rs +++ b/crates/vlog_linter/src/violation.rs @@ -2,12 +2,21 @@ use vlog_parser::span::TextRange; +use crate::severity::Severity; + /// One rule finding: which rule, what is wrong, where, and — sometimes — /// how to repair it. #[derive(Debug, Clone)] pub struct Violation { /// The reporting rule's stable kebab-case name. pub rule: &'static str, + /// How bad it is. **Set by the runner from the reporting rule**, not by + /// the rule's own `check` — [`crate::lint`] stamps every finding with + /// [`crate::Rule::severity`] before it is returned, so a rule cannot + /// contradict its own declared class. A violation built by hand (a rule's + /// unit test calling `check` directly) carries the placeholder below until + /// it goes through the runner. + pub severity: Severity, /// One sentence, lower case, no trailing period — the diagnostic line. pub message: String, /// Byte range the diagnostic points at. @@ -19,7 +28,7 @@ pub struct Violation { impl Violation { /// A finding with no automatic repair. pub fn new(rule: &'static str, message: impl Into, span: TextRange) -> Violation { - Violation { rule, message: message.into(), span, fix: None } + Violation { rule, severity: Severity::Warning, message: message.into(), span, fix: None } } /// The same finding, carrying a repair. diff --git a/crates/vlog_linter/src/visit.rs b/crates/vlog_linter/src/visit.rs index 4b2da20..5e73824 100644 --- a/crates/vlog_linter/src/visit.rs +++ b/crates/vlog_linter/src/visit.rs @@ -5,7 +5,8 @@ //! text and no children, so they are visited and matched by nothing. use vlog_parser::ast::{ - Fragment, GenBlock, GenElse, Item, ItemKind, ParamPort, SourceFile, Stmt, StmtKind, + Fragment, GenBlock, GenElse, Instantiation, Item, ItemKind, ParamPort, SourceFile, Stmt, + StmtKind, }; /// Calls `f` on every item in the file, nested items included. @@ -156,6 +157,17 @@ pub(crate) fn walk_param_ports(file: &SourceFile, f: &mut dyn FnMut(&ParamPort)) }); } +/// Calls `f` on every module instantiation of the file — a plain one, and the +/// one a `bind` directive carries, which is an ordinary instantiation written +/// somewhere else. +pub(crate) fn walk_instantiations(file: &SourceFile, f: &mut dyn FnMut(&Instantiation)) { + walk_items(file, &mut |item| match &item.kind { + ItemKind::Instantiation(inst) => f(inst), + ItemKind::Bind(bind) => f(&bind.inst), + _ => {} + }); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/vlog_linter/src/vscode.rs b/crates/vlog_linter/src/vscode.rs new file mode 100644 index 0000000..d5bcf7d --- /dev/null +++ b/crates/vlog_linter/src/vscode.rs @@ -0,0 +1,188 @@ +//! The VS Code lint settings, generated from the rule registry. +//! +//! `editors/vscode/package.json` declares one switch per severity class and +//! one per rule. Hand-written, that list would go stale the first time a rule +//! was added — the rule would ship with no way to turn it off from the +//! editor — so it is generated here instead, by the same crate that owns the +//! registry, exactly as [`crate::rules_markdown`] generates the rule +//! reference. +//! +//! Two consumers, one text: `cargo run -p vlog_linter --example +//! vscode_lint_settings` prints it for a human to paste in, and a test in +//! `lucisv_server` parses both this and `package.json` and fails when they +//! disagree. See `docs/features/linter-expansion-1/README.md`. + +use crate::registry::all_rules; +use crate::severity::Severity; +use crate::Rule; + +/// The setting a severity class's master switch is called. +pub fn severity_setting(severity: Severity) -> String { + format!("lucisv.lint.severity.{}", severity.as_str()) +} + +/// The setting one rule's toggle is called. +pub fn rule_setting(rule: &dyn Rule) -> String { + format!("lucisv.lint.rules.{}", rule.name()) +} + +/// The three words a per-rule toggle takes. +/// +/// A tri-state rather than a boolean, and deliberately: the ladder in +/// `lucisv_server::settings::enabled_rules` distinguishes a rule the user +/// *said something about* from one they left alone, and a plain boolean cannot +/// carry that — a client sends every setting in the section, its default +/// included, so "unset" and "set to the default" would arrive identically and +/// a per-rule toggle would silently override `select` and the class switches. +pub const RULE_CHOICES: [&str; 3] = ["default", "on", "off"]; + +/// The whole `lucisv.lint.severity.*` + `lucisv.lint.rules.*` block, as the +/// JSON object `package.json`'s `configuration.properties` holds them in. +/// +/// Two-space indentation with an eight-space margin, which is where those +/// properties sit in that file, so the text pastes in as it stands. +pub fn vscode_lint_settings() -> String { + let mut entries: Vec = Vec::new(); + for (i, severity) in Severity::ALL.into_iter().enumerate() { + entries.push(severity_entry(severity, 10 + i as u32)); + } + let mut order = 20; + for severity in Severity::ALL { + for rule in all_rules().into_iter().filter(|rule| rule.severity() == severity) { + entries.push(rule_entry(rule, order)); + order += 1; + } + } + format!("{{\n{}\n}}\n", entries.join(",\n")) +} + +/// One class's master switch. +fn severity_entry(severity: Severity, order: u32) -> String { + let description = format!( + "Run the **{word}** lint rules — {what}. Turning this off silences the whole class; \ + a per-rule toggle below still has the last word, and \ + `#lucisv.lint.ignore#` still removes a rule whatever else says. \ + Takes effect immediately — every open file is re-checked.", + word = severity.as_str(), + what = severity.describes(), + ); + format!( + " \"{id}\": {{\n\ + \x20 \"type\": \"boolean\",\n\ + \x20 \"default\": true,\n\ + \x20 \"order\": {order},\n\ + \x20 \"markdownDescription\": {description}\n\ + \x20 }}", + id = severity_setting(severity), + description = json_string(&description), + ) +} + +/// One rule's toggle. +fn rule_entry(rule: &'static dyn Rule, order: u32) -> String { + let description = format!( + "**{severity}** — {summary}. {default}", + severity = rule.severity().as_str(), + summary = rule.summary(), + default = default_sentence(rule), + ); + format!( + " \"{id}\": {{\n\ + \x20 \"type\": \"string\",\n\ + \x20 \"enum\": [{choices}],\n\ + \x20 \"enumDescriptions\": [\n\ + \x20 {leave},\n\ + \x20 \"Always run this rule.\",\n\ + \x20 \"Never run this rule.\"\n\ + \x20 ],\n\ + \x20 \"default\": \"default\",\n\ + \x20 \"order\": {order},\n\ + \x20 \"markdownDescription\": {description}\n\ + \x20 }}", + id = rule_setting(rule), + choices = RULE_CHOICES.iter().map(|c| json_string(c)).collect::>().join(", "), + leave = json_string(&format!("Leave it as it ships: {}", default_sentence(rule))), + description = json_string(&description), + ) +} + +/// How a rule's own default is said in one sentence — the same three cases +/// [`crate::rules_markdown`]'s Default column spells. +fn default_sentence(rule: &dyn Rule) -> String { + match (rule.default_on(), rule.needs_workspace()) { + (true, _) => "On by default.".to_string(), + (false, true) => "On where lucisv can see the project.".to_string(), + (false, false) => "Off by default.".to_string(), + } +} + +/// A JSON string literal. Hand-rolled, as the CLI's JSON output is: this crate +/// depends on `vlog_parser` and `std` alone, and a serialization framework for +/// one string shape is not a trade worth making. +fn json_string(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 2); + out.push('"'); + for c in text.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_rule_and_every_class_gets_an_entry() { + let json = vscode_lint_settings(); + for severity in Severity::ALL { + assert!(json.contains(&format!("\"{}\"", severity_setting(severity))), "{severity:?}"); + } + for rule in all_rules() { + let id = rule_setting(rule); + assert_eq!(json.matches(&format!("\"{id}\"")).count(), 1, "{id}"); + assert!( + json.contains(&format!("**{}** — {}.", rule.severity().as_str(), rule.summary())), + "{id}: description", + ); + } + } + + /// The toggles are ordered worst class first, then by name — which is how + /// the Settings UI groups them. + #[test] + fn the_order_numbers_group_by_severity_then_name() { + let json = vscode_lint_settings(); + let mut expected: Vec = Vec::new(); + for severity in Severity::ALL { + let mut names: Vec<&str> = all_rules() + .into_iter() + .filter(|rule| rule.severity() == severity) + .map(|rule| rule.name()) + .collect(); + names.sort_unstable(); + expected.extend(names.into_iter().map(str::to_string)); + } + let found: Vec = json + .lines() + .filter_map(|line| line.trim().strip_prefix("\"lucisv.lint.rules.")) + .filter_map(|rest| rest.split('"').next().map(str::to_string)) + .collect(); + assert_eq!(found, expected); + } + + #[test] + fn json_strings_are_escaped() { + assert_eq!(json_string("a\"b\\c"), "\"a\\\"b\\\\c\""); + assert_eq!(json_string("em — dash"), "\"em — dash\"", "UTF-8 passes through"); + } +} diff --git a/crates/vlog_linter/tests/cases/case_missing_default.lint b/crates/vlog_linter/tests/cases/case_missing_default.lint index df2c698..2ecd915 100644 --- a/crates/vlog_linter/tests/cases/case_missing_default.lint +++ b/crates/vlog_linter/tests/cases/case_missing_default.lint @@ -3,6 +3,7 @@ module m; always_comb begin case (s) //^ 5 case-missing-default +//^ 5 incomplete-assignment 0: x = 1; endcase end @@ -33,6 +34,7 @@ module m; always_comb begin // lucisv: waive case-missing-default case (s) +//^ 5 incomplete-assignment 0: x = 1; endcase end diff --git a/crates/vlog_linter/tests/cases/declarations.lint b/crates/vlog_linter/tests/cases/declarations.lint new file mode 100644 index 0000000..39103fe --- /dev/null +++ b/crates/vlog_linter/tests/cases/declarations.lint @@ -0,0 +1,83 @@ +# a packed dimension that counts upwards +#select packed-dimensions-range-ordering +module m; + logic [0:7] up; +//^ 9 packed-dimensions-range-ordering + logic [0:WIDTH-1] also_up; +//^ 9 packed-dimensions-range-ordering +endmodule +==== +# the decreasing form, a one-bit range, and an unpacked array +#select packed-dimensions-range-ordering +module m; + logic [7:0] down; + logic [WIDTH-1:0] symbolic; + logic [0:0] one_bit; + logic [LO:HI] unknowable; + logic ascending_array [0:3]; +endmodule +==== +# a negative constant written into a dimension +#select forbid-negative-array-dim +module m; + logic [-1:0] v; +//^ 10 forbid-negative-array-dim + logic q [-1]; +//^ 12 forbid-negative-array-dim +endmodule +==== +# a subtraction is not a negative literal +#select forbid-negative-array-dim +module m; + logic [WIDTH-1:0] v; + logic q [DEPTH]; + parameter int P = -1; +endmodule +==== +# an untyped formal is a one-bit logic +#select explicit-function-task-parameter-type +module m; + function void f(input a); +//^ 19 explicit-function-task-parameter-type + endfunction +endmodule +==== +# a continuation formal inherits the type in force +#select explicit-function-task-parameter-type +module m; + function void f(input int a, b); + endfunction + task t(input logic [7:0] c); + endtask +endmodule +==== +# a positional connection list of more than one port +#select module-port +module m; + sub u_sub (a, b, c); +//^ 7 module-port +endmodule +==== +# named connections, a wildcard, and a single positional one +#select module-port +module m; + sub u1 (.a(x), .b(y)); + sub u2 (.*); + sub u3 (a); + sub u4 (); +endmodule +==== +# more than one positional parameter override +#select module-parameter +module m; + sub #(8, 4) u_sub (); +//^ 3 module-parameter +endmodule +==== +# named overrides, and a single positional one +#select module-parameter +module m; + sub #(.Width(8), .Depth(4)) u1 (); + sub #(8) u2 (); + sub u3 (); +endmodule diff --git a/crates/vlog_linter/tests/cases/labels_and_scopes.lint b/crates/vlog_linter/tests/cases/labels_and_scopes.lint new file mode 100644 index 0000000..25ad198 --- /dev/null +++ b/crates/vlog_linter/tests/cases/labels_and_scopes.lint @@ -0,0 +1,82 @@ +# an end label that names another block is a compile error +#select mismatched-labels +module m; + always_comb begin : fetch + x = 1; + end : decode +//^ 9 mismatched-labels +endmodule +==== +# a footer label on a block that has none is one too +#select mismatched-labels +module m; + always_comb begin + x = 1; + end : blk +//^ 9 mismatched-labels +endmodule +==== +# a matching pair, and a footer that was simply not written +#select mismatched-labels +module m; + always_comb begin : blk + x = 1; + end : blk + always_comb begin : other + y = 1; + end +endmodule : m +==== +# every construct with a footer label is checked +#select mismatched-labels +package p; + function void f(); + endfunction : g +//^ 17 mismatched-labels +endpackage : q +//^ 14 mismatched-labels +==== +# two declarations of one name in one scope +#select duplicate-declaration +module m; + logic a; + logic a; +//^ 9 duplicate-declaration +endmodule +==== +# a non-ANSI port is completed by its body declarations, three times legally +#select duplicate-declaration +module m (clk); + input clk; + logic clk; +endmodule +==== +# conditional arms never coexist, so they are not duplicates +#select duplicate-declaration +module m; +`ifdef X + logic b; +`else + logic b; +`endif +endmodule +==== +# a block-local hiding a module signal is shadowing, not duplication +#select instance-shadowing +module m; + logic count; + always_comb begin : blk + logic count; +//^ 11 instance-shadowing + count = 1'b0; + end +endmodule +==== +# two modules may each declare the same name +#select instance-shadowing +module a; + logic data; +endmodule +module b; + logic data; +endmodule diff --git a/crates/vlog_linter/tests/cases/literals.lint b/crates/vlog_linter/tests/cases/literals.lint new file mode 100644 index 0000000..81ec835 --- /dev/null +++ b/crates/vlog_linter/tests/cases/literals.lint @@ -0,0 +1,61 @@ +# a literal wider than its declared width is truncated +#select truncated-numeric-literal +module m; + assign x = 4'hFFF; +//^ 14 truncated-numeric-literal +endmodule +==== +# leading zeros, an exact fit and an all-unknown literal are all fine +#select truncated-numeric-literal +module m; + assign a = 8'h0FF; + assign b = 32'hdead_beef; + assign c = 3'hz; + assign d = 7'hzz; +endmodule +==== +# an unsized literal has no width to overflow +#select truncated-numeric-literal +module m; + assign x = 'hffff_ffff; +endmodule +==== +# a short binary literal is padded to its declared width +#select undersized-binary-literal +module m; + assign x = 8'b1; +//^ 14 undersized-binary-literal +endmodule +---- +module m; + assign x = 8'b00000001; +//^ 14 undersized-binary-literal +endmodule +==== +# an unknown extends itself rather than zero-filling +#select undersized-binary-literal +module m; + assign x = 4'bz; +//^ 14 undersized-binary-literal +endmodule +---- +module m; + assign x = 4'bzzzz; +//^ 14 undersized-binary-literal +endmodule +==== +# zero is exempt, as it is in verible: `lint_zero` defaults off +#select undersized-binary-literal +module m; + assign a = 2'b0; + assign b = 32'b0; + assign c = 4'b1010; +endmodule +==== +# only binary is judged, and only when the literal says its width +#select undersized-binary-literal +module m; + assign a = 8'h1; + assign b = 8'd1; + assign c = 'b1; +endmodule diff --git a/crates/vlog_linter/tests/cases/statements.lint b/crates/vlog_linter/tests/cases/statements.lint new file mode 100644 index 0000000..3e500e5 --- /dev/null +++ b/crates/vlog_linter/tests/cases/statements.lint @@ -0,0 +1,98 @@ +# a control statement whose whole body is a `;` +#select suspicious-semicolon +module m; + always_comb begin + if (ready); +//^ 15 suspicious-semicolon + while (busy); +//^ 17 suspicious-semicolon + end +endmodule +==== +# a real body, and the way to write a deliberately empty one +#select suspicious-semicolon +module m; + always_comb begin + if (ready) x = 1; + forever begin end + ; + end +endmodule +==== +# a void cast around something that is not a call discards nothing +#select void-cast +module m; + initial begin + void'(x); +//^ 5 void-cast + void'(f()); + void'(obj.randomize() with { a inside {[0:3]}; }); + end +endmodule +==== +# defparam reaches into another scope +#select forbid-defparam +module m; + sub u (); + defparam u.WIDTH = 8; +//^ 3 forbid-defparam +endmodule +==== +# the named override is what the rule wants instead +#select forbid-defparam +module m; + sub #(.WIDTH(8)) u (); +endmodule +==== +# the forbidden system tasks, and the replacements beside them +#select invalid-system-task-function +module m; + initial begin + a = $random(); +//^ 9 invalid-system-task-function + b = $psprintf("%0d", a); +//^ 9 invalid-system-task-function + c = $urandom(); + d = $sformatf("%0d", c); + end +endmodule +==== +# a plusarg should be read as a value, not tested for by prefix +#select plusarg-assignment +module m; + initial begin + if ($test$plusargs("fast")) go = 1; +//^ 9 plusarg-assignment + if ($value$plusargs("speed=%0d", speed)) go = 1; + end +endmodule +==== +# a variable written only under an if infers a latch +#select incomplete-assignment +module m; + always_comb begin + if (en) y = a; +//^ 5 incomplete-assignment + end +endmodule +==== +# a default assignment before the branch is the repair +#select incomplete-assignment +module m; + always_comb begin + y = 1'b0; + if (en) y = a; + end +endmodule +==== +# a case with a default writes every arm, so the if after it is covered +#select incomplete-assignment +module m; + always_comb begin + case (s) + 0: y = a; + default: y = b; + endcase + if (en) y = 1'b1; + end +endmodule diff --git a/crates/vlog_semantic/src/bind/mod.rs b/crates/vlog_semantic/src/bind/mod.rs index db7eb6d..ae6625c 100644 --- a/crates/vlog_semantic/src/bind/mod.rs +++ b/crates/vlog_semantic/src/bind/mod.rs @@ -24,7 +24,7 @@ use vlog_parser::ast::*; use vlog_parser::span::TextRange; use vlog_parser::token::is_keyword; -use crate::model::{Scope, ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind}; +use crate::model::{Duplicate, Scope, ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind}; /// A recorded use, waiting for pass two to say what it names. pub(crate) struct Pending { @@ -129,6 +129,9 @@ pub(crate) struct Binder<'a> { pub(crate) scopes: Vec, pub(crate) symbols: Vec, pub(crate) pending: Vec, + /// Every name a scope bound a second time, in the order they were + /// written. Purely a record — see [`Duplicate`]. + pub(crate) duplicates: Vec, deferred: Vec>, /// While a `randomize() with { ... }` block is being bound: the head of /// the object being randomized, so a bare name inside the block is @@ -159,6 +162,7 @@ impl<'a> Binder<'a> { scopes: vec![file], symbols: Vec::new(), pending: Vec::new(), + duplicates: Vec::new(), deferred: Vec::new(), with_head: None, bind_target: None, @@ -201,7 +205,15 @@ impl<'a> Binder<'a> { if name.is_empty() { return None; } - if self.scopes[scope.0 as usize].names.contains_key(name) { + if let Some(&first) = self.scopes[scope.0 as usize].names.get(name) { + self.duplicates.push(Duplicate { + name: name.to_string(), + name_span, + decl_span, + kind, + first, + scope, + }); self.use_name(scope, name, name_span, Target::Lexical); return None; } diff --git a/crates/vlog_semantic/src/lib.rs b/crates/vlog_semantic/src/lib.rs index 9488d76..3609d47 100644 --- a/crates/vlog_semantic/src/lib.rs +++ b/crates/vlog_semantic/src/lib.rs @@ -28,8 +28,8 @@ mod workspace; pub use facts::{record_path, FACTS_FORMAT}; pub use model::{ - DocumentSymbol, Import, MemberSite, Reference, ReferenceId, Resolution, Scope, ScopeId, - ScopeKind, Symbol, SymbolId, SymbolKind, + DocumentSymbol, Duplicate, Import, MemberSite, Reference, ReferenceId, Resolution, Scope, + ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind, }; pub use workspace::{ index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition, @@ -54,6 +54,9 @@ pub struct Semantics { symbol_positions: Vec<(TextRange, SymbolId)>, /// Non-empty reference-name spans, sorted by start for cursor lookup. reference_positions: Vec<(TextRange, ReferenceId)>, + /// Every name a scope bound twice, in source order. Recorded by the + /// binder and judged by nobody here — see [`Duplicate`]. + duplicates: Vec, /// Every symbol id, sorted by the name it declares, ties in declaration /// order — so looking a name up is a binary search rather than a walk of /// every symbol. A side table rather than a `HashMap` because @@ -75,7 +78,7 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics { // only guaranteed to exist once the whole file is bound. binder.bind_deferred(); - let bind::Binder { mut scopes, symbols, pending, .. } = binder; + let bind::Binder { mut scopes, symbols, pending, duplicates, .. } = binder; link_imports(&mut scopes, &symbols); let mut references = Vec::with_capacity(pending.len()); @@ -120,7 +123,16 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics { // would have seen, which is what makes swapping the two an identity. let mut by_name: Vec = (0..symbols.len() as u32).map(SymbolId).collect(); by_name.sort_by(|a, b| symbols[a.0 as usize].name.cmp(&symbols[b.0 as usize].name)); - Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions, by_name } + Semantics { + scopes, + symbols, + references, + uses, + duplicates, + symbol_positions, + reference_positions, + by_name, + } } /// Point every import at the package it names, when this file declares it. @@ -153,6 +165,16 @@ impl Semantics { &self.references } + /// Every name a scope bound a second time, in source order. + /// + /// Additive, and read by one caller: the `duplicate-declaration` lint. + /// Nothing else in the crate consults it, and no existing answer changed + /// when it was added — a redeclaration is still a reference to the first + /// declaration everywhere it was one before. + pub fn duplicates(&self) -> &[Duplicate] { + &self.duplicates + } + /// The file scope. pub fn file_scope(&self) -> ScopeId { ScopeId(0) diff --git a/crates/vlog_semantic/src/model.rs b/crates/vlog_semantic/src/model.rs index 85046a5..5aed66e 100644 --- a/crates/vlog_semantic/src/model.rs +++ b/crates/vlog_semantic/src/model.rs @@ -155,6 +155,37 @@ pub struct Symbol { pub child_scope: Option, } +/// A name a scope bound **twice**: the second declaration, and the first one +/// that already held the name. +/// +/// The binder's rule is that a redeclaration becomes a *reference* to the +/// first declaration rather than a second symbol — which is exactly what makes +/// a non-ANSI port's body declaration attach to its header port, and an +/// out-of-body method definition attach to its prototype. That is the right +/// answer for hover, rename and go-to-definition, and it means the fact that a +/// second declaration was written is not otherwise recoverable from the +/// tables. This records it, so a caller who cares (the `duplicate-declaration` +/// lint) can ask; every existing caller is unaffected. +/// +/// **Recorded, not judged.** Several of these are perfectly legal, and telling +/// which is the caller's business: see +/// `docs/features/linter-expansion-1/README.md`. +#[derive(Debug, Clone)] +pub struct Duplicate { + /// The name declared twice. + pub name: String, + /// Byte range of the **second** declaration's name, as written. + pub name_span: TextRange, + /// Byte range of the whole second declaration. + pub decl_span: TextRange, + /// What kind of declaration the second one is. + pub kind: SymbolKind, + /// The declaration that already held the name. + pub first: SymbolId, + /// The scope both were written in. + pub scope: ScopeId, +} + /// What a [`Reference`] turned out to name. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Resolution { diff --git a/docs/features/linter-expansion-1/README.md b/docs/features/linter-expansion-1/README.md new file mode 100644 index 0000000..acd8722 --- /dev/null +++ b/docs/features/linter-expansion-1/README.md @@ -0,0 +1,618 @@ +# linter expansion, wave 1 (TODO §33) + +## Goal + +Grow the linter from 17 rules toward what Verible's 62 cover, and give a user +a way to say which of them they want. Three things, in one lane because they +touch the same registry: a **severity** on every rule (`error` / `warning` / +`style`) carried end to end — into `--select`/`--ignore`, the CLI diagnostic +line, the JSON output, the editor's squiggle colour and the generated rule +reference; **per-rule toggles in VS Code**, generated from the registry so a +rule cannot ship without its switch, with one documented precedence for the +five ways a rule can be turned on or off; and the **rules that matter first** — +the ones that say the code would not compile (Error) and the ones that say it +does not mean what it says (Warning). The Style family and per-rule options are +wave 2 (§34). 17 rules → **36**. + +## Assumptions + +- **Severity is a property of the rule, not of the finding.** Every violation a + rule reports is in the same class, so the runner stamps it + (`vlog_linter::lint`) rather than each `check` remembering to. A rule whose + findings would want two classes is two rules. +- **`Error` means "a tool would refuse this file", and a rule may only claim + it when it is certain.** Every Error-class rule added here is silent whenever + the workspace cannot answer: a file that did not fully parse, a module that + is not indexed or is indexed twice, a name a macro produces, a fragment + written to be `` `include``d. A wrong accusation in this class is worse than + a hundred missed ones, and the opentitan census below is what turned that + sentence into code — every Error rule's first measurement found false + positives, and each one became an exclusion with a test. +- **A severity word is not a rule name.** `error`, `warning` and `style` are + accepted wherever a rule name is, and + `registry::every_rule_has_a_severity_and_no_name_shadows_a_class` pins that + no rule may be named after a class. +- **The editor's classes map to LSP severities 1/2/3.** Style is + `INFORMATION`, not `HINT`: a hint is invisible in most themes, which would + make the style rules look broken rather than quiet. +- **The VS Code settings are generated, never hand-written.** The generator is + the registry; the drift test in `lucisv_server` is what makes that true after + the next rule is added. +- **A file that does not parse gets no structural opinion.** `LintContext:: + parsed_cleanly` is the shared guard: error recovery unwinds out of the + construct it failed in, so declarations that followed are bound in whatever + scope recovery landed in. Three rules ask it before saying anything. +- **Verible's defaults are matched unless §33 says otherwise**, options + included: `undersized-binary-literal` exempts a zero literal because + Verible's `lint_zero` defaults off, and checks binary only because its `oct` + and `hex` default off. Four rules Verible ships **off** are on here by §33's + instruction: `mismatched-labels`, `suspicious-semicolon`, + `instance-shadowing`, `forbid-negative-array-dim`. + +## Handshakes + +**Consumed** + +- `vlog_parser::ast` — unchanged. The new syntactic rules read the same nodes + the existing ones do, through `crate::visit` and the new `crate::decls`. +- `vlog_semantic::words::harvest_raw` — already public; `undeclared-identifier` + reads it for the "a macro writes this name down" exclusion. +- `vlog_semantic::WorkspaceIndex::{units, members_of}` — already public; the + server answers `module_interface` from them. + +**Requested and taken — `vlog_semantic`, additive (flag for the lead)** + +`duplicate-declaration` could not be answered from the existing tables: the +binder turns a redeclaration into a *reference* to the first declaration +(which is what makes a non-ANSI port's body declaration attach to its header +port), so the fact that a second declaration was written is not recoverable. +As §33.2 anticipated, one additive query was added: + +- `vlog_semantic::Duplicate` — name, both spans, kind, the first symbol, the + scope. +- `Binder::duplicates` records one on the path that already existed + (`declare`'s "already bound" arm); nothing else in that function changed. +- `Semantics::duplicates() -> &[Duplicate]`. + +**No `FACTS_FORMAT` change**: nothing was added to `FileFacts`, nothing is +persisted, and no existing answer moved — a redeclaration is still a reference +to the first declaration everywhere it was one before. `vlog_semantic`'s own +tests are unchanged and green. + +**Requested and taken — `lucisv_server/src/server/notification.rs` (flag for +the lead)** + +Two lines. `apply_settings` republishes every open file when the lint +*selection* changes, and compares it through a private `lint_selection()` that +cloned `lint_select` and `lint_ignore`. §33.1 requires the same republish when +a class switch or a per-rule toggle changes, so that function now calls the new +`settings::lint_selection(&ClientSettings)`, which returns all four. The file +is not on this lane's ownership list; the change is mechanically required by +§33.1's "changing any of them republishes every open file", cannot collide with +the §31 lane (different crate), and is called out here and in the lane report +so the lead can rule on it at merge. + +**Promised (new public surface of `vlog_linter`)** + +- `Severity` (`Error` / `Warning` / `Style`) with `as_str`, `from_name`, + `describes` and `ALL`. +- `Rule::severity(&self) -> Severity` — **no default**; every rule states one. + *A consumer implementing `Rule` outside this crate must add it.* No such + consumer exists. +- `Violation::severity` — set by `lint`, not by the reporting rule. +- `rules_named(&str) -> Option>`; `select_rules` now + accepts severity words on either list. +- `LintContext::parsed_cleanly()`, `LintContext::module_interface()`. +- `MentionOracle::module_interface(&str) -> Option` — a + **defaulted** method returning `None`, so every existing implementor keeps + compiling and answers "I cannot say", which leaves the two rules that ask it + silent. +- `ModuleInterface { ports, parameters }` with `has_port` / `has_parameter`. +- `module_interfaces(&SourceFile)` — the CLI's reading of a parse. +- `ParsedSource::file()`. +- `vscode_lint_settings()`, `rule_setting`, `severity_setting`, + `RULE_CHOICES`. +- `rules_markdown()` gains a Severity column and groups its sections by class. + +**Promised (CLI)** — text output is +`FILE:LINE:COL: error|warning|style: message [rule]`; JSON gains `"severity"`. +Exit codes unchanged. + +**Promised (server)** — a lint diagnostic's `severity` is its rule's class; +`lint::enabled_rules(settings, has_oracle)` is the one ladder. + +## Status / TODO + +- [x] 33.0 `Severity` on every rule; select/ignore by severity; CLI text/JSON; + editor severities; `--rules-doc` grouped +- [x] 33.1 package.json toggles generated + drift test; `enabled_rules` + precedence pinned; republish on change +- [x] 33.2 Error rules: mismatched-labels, duplicate-declaration, + undeclared-identifier (measured; default decided by the count), + unknown-port, unknown-parameter +- [x] 33.3 Warning rules: the thirteen listed, each with tests and an + opentitan count +- [x] 33.4 docs; measurements table below +- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820 + byte-identical; opentitan read-only census + timing +- [ ] QA + +## Measurements + +**Corpus** = lucisv's 860-file corpus (`corpus/`). **opentitan** = a read-only +`lucisv check hw` over 3 975 files at `/Users/guoliangchen/repo/opentitan` +(`git status --porcelain` after every run showed only the three files that were +already modified before this lane started). "Sample" is findings read and +classified, out of ten where there were ten. + +| Rule | Sev | Default | Verible equivalent (its default) | Corpus | opentitan | Sample: true / false / judgment | +|---|---|---|---|---:|---:|---| +| `mismatched-labels` | error | on | `mismatched-labels` (off) → **on** | 0 | 1 | 1 / 0 / 0 | +| `duplicate-declaration` | error | on | none | 0 | 0 | — (18 before the exclusions, all false) | +| `undeclared-identifier` | error | on (project) | none | 5 | 5 | 5 / 0 / 0 | +| `unknown-port` | error | on (project) | none | 0 | 40 | 6 / 0 / 0 | +| `unknown-parameter` | error | on (project) | none | 1 | 4 | 4 / 0 / 0 | +| `forbid-defparam` | warning | on | `forbid-defparam` (on) | 0 | 0 | — | +| `invalid-system-task-function` | warning | on | same (on) | 8 | 23 | 10 / 0 / 0 | +| `truncated-numeric-literal` | warning | on | same (on) | 0 | 0 | — (50 before the all-unknown exempt, all false) | +| `undersized-binary-literal` | warning | on, safe fix | same (on, `lint_zero` off) | 11 | 6 | 6 / 0 / 0 | +| `suspicious-semicolon` | warning | on | same (off) → **on** | 3 | 5 | 5 / 0 / 0 | +| `packed-dimensions-range-ordering` | warning | on | same (on) | 0 | 4 | 4 / 0 / 0 | +| `module-port` | warning | on | same (on) | 44 | 161 | 7 / 0 / 3 | +| `module-parameter` | warning | on | same (on) | 2 | 0 | 2 / 0 / 0 | +| `explicit-function-task-parameter-type` | warning | on | same (on) | 1 | 5 | 5 / 0 / 0 | +| `plusarg-assignment` | warning | on | same (on) | 19 | 13 | 10 / 0 / 0 | +| `instance-shadowing` | warning | on | same (off) → **on** | 28 | 129 | 3 / 0 / 0 | +| `forbid-negative-array-dim` | warning | on | same (off) → **on** | 0 | 0 | — | +| `void-cast` | warning | on | same (on), different subject | 0 | 0 | — (1 before the `with` fix, false) | +| `incomplete-assignment` | warning | on | none | 3 | 0 | 3 / 0 / 0 (corpus) | + +### Why a Verible-default-on rule fires on a "Verible-clean" tree + +opentitan is lint-clean under Verible **for the filesets its `dvsim` lint +configurations name** — `hw/top_*/lint/*_lint_cfgs.hjson`, which cover RTL and +a chosen slice of DV. `lucisv check hw` covers all 3 975 files, including +`hw/vendor/` (third-party: ibex, pulp, riscv-dv), `hw/ip/*/pre_dv`, +`hw/ip/*/pre_sca` and `hw/ip/*/fpv`, none of which that flow lints. Every +finding of a Verible-equivalent rule sits in one of those: + +- `module-port` (161): every one in `hw/top_*/dv/`, mostly autogenerated + `tb__xbar_connect.sv` interface instantiations (`tl_if tl_if(clk, rst_n)`). + The three "judgment" samples are exactly that idiom — a two-port clocking + interface connected positionally, which Verible would flag too. +- `undersized-binary-literal` (6): all in `hw/vendor/`. +- `invalid-system-task-function` (23), `plusarg-assignment` (13), + `explicit-function-task-parameter-type` (5), + `packed-dimensions-range-ordering` (4): DV, vendored and pre-silicon + directories. +- opentitan's own Verible config + (`hw/lint/tools/veriblelint/lowrisc-styleguide.rules.verible_lint`) sets only + four options and disables one rule; none of them is a rule this wave added. + +### False positives found by the census and closed + +Every one of these was found by reading opentitan findings, and every one is +now a named exclusion with a test beside it: + +| Rule | Before | Cause | After | +|---|---:|---|---:| +| `duplicate-declaration` | 18 | error recovery in a 454-error UVM file rebinds every method local at file scope; enum **name ranges** (`Gpr[0:2]`); non-ANSI port completion | 0 | +| `undersized-binary-literal` | 456 | `2'b0` — Verible's `lint_zero` defaults **off** | 6 | +| `truncated-numeric-literal` | 50 | `3'hz`, `7'hzz`: one hex digit is four bits, so an all-unknown literal always "overflows" | 0 | +| `incomplete-assignment` | 3 | a temporary the block declares; a partial write before the branch; a `case` with a `default` covering every arm | 0 | +| `void-cast` | 1 | `void'(randomize(x) with { … })` — a call wearing a postfix clause | 0 | +| `undeclared-identifier` | 94 | `` `include``d **fragments** (a module body with no module around it: 85 of the 94); a generate label reached hierarchically | 5 | + +### `undeclared-identifier`: the default decision + +§33.2 made the default conditional on the count of *unexplained* findings on +opentitan being zero. After the exclusions above it reports **five** findings, +in one file, on both trees: `ibex/dv/formal/spec/spec_api.sv` connects +`.mhartid_out(mhart_id_o)`, `.mimpid_out(mimp_id_o)`, `.minstret_in(minstret_i)`, +`.minstret_out(minstret_o)` and `.mvendorid_out(mvendor_id_o)` to names its +module header never declares — implicit one-bit nets, which is exactly what the +rule exists to find. Unexplained: **0**. It therefore ships on wherever there +is a project, the same terms `unused-signal` and `undriven-net` run on. + +*The residual risk, for the lead:* the rule's safety rests on the census +covering the whole project. A deliberately partial run (`lucisv check +hw/ip/uart` alone) has a smaller census and could accuse a name declared in a +directory the run did not include. The same is structurally true of +`unused-signal`, but there the failure mode is a false *negative* and here it +is a false positive. `--ignore undeclared-identifier`, `[lint] ignore` and the +per-rule VS Code toggle are all off switches for it. + +### Timing — `lucisv check hw` over opentitan (3 975 files) + +| Build | Wall (best of 3) | +|---|---:| +| 0.34.0 baseline (`/tmp/lucisv-0.34.0-baseline`) | 0.91 s | +| this lane, default rules | 0.83 s | +| this lane, `--ignore unknown-port --ignore unknown-parameter` | 0.66 s | + +The interface half of the CLI census costs a **parse** of every file on top of +the lex the word census already paid for (~0.17 s here), and is built only when +`unknown-port` or `unknown-parameter` is enabled. Even with it the run is +*faster* than 0.34.0, because the same pass now harvests the word census from +the parse's own tokens instead of lexing the text a second time. The nineteen +new rules' own checking cost is inside the noise. + +### Corpus and formatter gates + +- `scripts/corpus_gate.sh corpus` → `{"passing":814,"total":820,"pct":99.3}`, + the same six failures, exit 0. +- `--stdout` over all 860 corpus files, byte-compared against the 0.34.0 + baseline binary: **860 checked, 0 differing**. The formatter is untouched. +- `node editors/vscode/smoke.js target/debug/lucisv-server` → OK, 20 messages. + +## Work log + +### 2026-09-03 — 33.0, severity end to end + +- New `vlog_linter::severity` (`Severity`, `as_str`/`from_name`/`describes`/ + `ALL`), `Rule::severity` with no default, `Violation::severity`. +- **The runner stamps.** `lint()` ends with `stamp_severities`, which looks + each finding's rule up in the registry. One place rather than one per rule, + and it also covers the `unused-waiver` findings, which the waiver scanner + builds without a rule's `check` ever running. Pinned by + `the_runner_stamps_every_finding_with_its_rules_severity`. +- The seventeen assignments §33.0 listed are pinned as a table test, so a rule + changing class is a deliberate edit. +- `select_rules` goes through the new `rules_named`. `--ignore style` and + `[lint] ignore = ["style"]` therefore work with no change in + `lucisv_core::config` (it never validated names). +- CLI text gained the severity word; JSON gained `"severity"`. The server maps + Error/Warning/Style to ERROR/WARNING/INFORMATION. Four existing tests + asserted `WARNING` for style rules and were updated in place with the reason + in a comment. +- `rules_markdown` grew a Severity column, a per-rule `- Severity:` line and + three class headings. + +### 2026-09-03 — 33.1, the toggles + +- New `vlog_linter::vscode` generates the whole `lucisv.lint.severity.*` + + `lucisv.lint.rules.*` block; `examples/vscode_lint_settings.rs` prints it. +- **Deviation from §33.1, deliberate.** The brief asked for "one boolean per + rule, default = the rule's default", and for a precedence rung that fires + only on an *explicitly set* toggle. Those two cannot both hold: a client + sends the whole section with every key at its default, so a boolean cannot + distinguish "unset" from "set to the shipped value", and rung 4 would then + silently override `select` and the class switches for every user. The + toggles are therefore a three-word enum — `default` / `on` / `off`, default + `default` — which is tri-state, renders as a dropdown in the Settings UI + (a `["boolean","null"]` schema renders as raw JSON), and states the rule's + own default in its description and in its `enumDescriptions`. +- `settings.rs` reads them into `lint_severity: BTreeMap` and + `lint_rules: BTreeMap` (present only for `on`/`off`), on this + module's standing rule that an unreadable value leaves the shipped default. + The `select`/`ignore` validator now keeps severity words. +- `lint::enabled_rules(settings, has_oracle)` is the one ladder, documented + rung by rung and pinned by `the_enabled_rules_ladder_is_the_documented_one`, + plus `a_class_switch_changes_what_the_server_publishes` through the real + diagnostics path. +- The drift guard `the_vscode_lint_toggles_match_the_registry` parses both + `package.json` and the generator's output and compares them as JSON values. + It caught the stale manifest three times during this lane, which is what it + is for. + +### 2026-09-03 — 33.2 and 33.3, the rules + +- Nineteen rules, one file each, each with unit tests holding true positives + **and** near-misses, and a `.lint` case in one of the four new case files + (`literals`, `labels_and_scopes`, `statements`, `declarations`). +- Two new shared walkers rather than growing `visit.rs` past its one sentence: + `visit::walk_instantiations` (a plain instantiation and a `bind`'s), and a + new `decls.rs` for every `DataType` and every `Dim` in a file, packed and + unpacked told apart. A new `literal.rs` reads a sized based literal once for + the two width rules. +- `interfaces.rs` reads a parse's module headers into a `ModuleInterface`, for + the CLI census. A header carrying **any** directive between its ports or + parameters is reported unknowable rather than short: telling an `` `ifdef`` + arm from a macro standing where a port belongs would be a second + preprocessor, and a short list is what turns a legal connection into an + accusation. +- `MentionOracle` gained one defaulted method. The CLI implements it from a + new interface half of `Census`, built only when a rule asks; the server + implements it from the workspace index, refusing a module the index holds + more than once. +- `LintContext::parsed_cleanly()` is the shared "this file's structure cannot + be trusted" guard, asked by `duplicate-declaration`, `instance-shadowing` + and `undeclared-identifier`. +- One `#[allow(clippy::large_enum_variant)]` was added, on + `context::SemanticsSlot`: `Semantics` grew past clippy's threshold when it + gained its `duplicates` table, and boxing the lazy slot would add an + allocation to the path that exists to avoid one. The reason is in a comment + above it. +- Every rule was measured on opentitan before it was called done; six false + positive classes were found that way and closed, each with a test naming the + file it came from. The counts are in Measurements above. + +### 2026-09-03 — 33.4, docs + +- README.md "Linting": the severity section, the class table, the ladder for + `--select error` / `--ignore style`, and a 36-row rule table. +- `editors/vscode/README.md`: two Diagnostics rows, six Settings rows and the + five-rung precedence. +- `docs/site/.../reference/rules.md`: the badge, the intro paragraphs on + severity and on the Error-class discipline, a Severity column, and one + hand-written section per new rule — with a note that `--rules-doc` is the + generated truth. A test-free page, so it is checked by hand against + `--rules-doc`'s section list (they match exactly). + +## QA log + +### 2026-09-03 — verification of 33.0–33.4, verdict PASS + +Scope: everything on the Status/TODO list except the last box. Worked +entirely in `.claude/worktrees/lint-1` (branch `lint-1`, based on 965c4ee, +uncommitted); every experiment that needed a modified registry or a rebuilt +baseline binary ran in a throwaway `git worktree` created from 965c4ee or +999edd0 and removed when done (`baseline-965c4ee`, `throwaway-lint1`, +`baseline-rebuild` — none left behind). Opentitan was touched read-only; +`git -C opentitan status --porcelain` showed only the three pre-existing +files (`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`, +`hw/top_earlgrey/ip/ast/rtl/ast.sv`) before and after every run in this pass. + +**1. Gates.** +- `cargo fmt --all -- --check`: clean. +- `cargo clippy --all-targets --workspace`: clean. The first run was a cache + hit (0.11 s, nothing recompiled) so I re-ran it against a throwaway + `--target-dir` to force a full rebuild of all nine workspace crates — still + 0 warnings, 14.5 s. The one new `#[allow(clippy::large_enum_variant)]` (on + `vlog_linter::context::SemanticsSlot`) carries an explanatory comment. +- `cargo test --workspace --no-fail-fast`: 48 binaries, **3383 passed, 0 + failed, 42 ignored** — matches the dev's reported numbers exactly. +- `git diff --stat 965c4ee -- crates/vlog_formatter`: empty. `git diff + --name-only 965c4ee`: confined to the §33 ownership list plus the two + disclosed handshake files (`crates/vlog_semantic/src/{bind/mod.rs,lib.rs, + model.rs}`, `crates/lucisv_server/src/server/notification.rs`) — nothing + else. +- `cargo build --release -p lucisv`: clean. `--stdout` over all 860 corpus + files vs a freshly rebuilt 0.34.0 baseline (999edd0; `965c4ee` has no + crate diff from it, confirmed with `git diff --stat 999edd0 965c4ee -- + crates/`): **860 checked, 0 differing**. (The originally-referenced + `/tmp/lucisv-0.34.0-baseline` was removed by the environment between + session restarts; rebuilding it from 999edd0 in a throwaway worktree + produced a byte-identical binary — same size, 2 342 144 bytes — and the + check was redone against the rebuild with the same 860/0 result.) +- `scripts/corpus_gate.sh corpus`: `{"passing":814,"total":820,"pct":99.3}` — + matches. +- vsix smoke (`node editors/vscode/smoke.js target/debug/lucisv-server`): OK, + 20 messages. + +**2. Severity plumbing.** Built a file with one violation of each class +(`no-tabs`/style, `wire-reg-mixup`/error, `always-comb-blocking`/warning). +Text output: `FILE:LINE:COL: error|warning|style: message [rule]`, exactly. +JSON: every finding carries `"severity"`; the baseline's JSON for the same +file has no such key. Exit code (1) matches the baseline binary's on the same +file. `--select style` → only the style finding; `--ignore warning` → warning +dropped, other two kept; `--select error --ignore mismatched-labels` → only +`wire-reg-mixup` (the only error-class rule this file trips); `--select +bogus` → `error: unknown rule: bogus (severities: error, warning, style; +known rules: ...)`, exit 2. `[lint] ignore = ["style"]` in `lucisv.toml` → +style dropped, same as `--ignore style`. `--rules-doc`: 36 rules, each with a +severity; the seventeen original assignments in the table match +`the_original_seventeen_keep_the_classes_they_were_given` exactly +(`multiply-driven`/error, `wire-reg-mixup`/error, five warnings, nine +styles). + +**3. Editor toggles, through the real server.** No existing e2e test in +`tests/e2e.rs` exercises `lucisv.lint.severity.*` or `lucisv.lint.rules.*` +over the wire (only the pre-existing `lucisv.lint.ignore` case is there); the +new settings are otherwise covered by `settings.rs` and `lint.rs` unit tests +only. I drove the real `target/debug/lucisv-server` binary myself, framing +JSON-RPC by hand (same Content-Length model as `tests/e2e.rs`'s `talk()`), +one whole session per scenario so ordering could not be ambiguous: +- (a) `severity.style=false` on a file with all three classes → style + vanishes, error/warning stay. Correct. +- (b) `rules.always-comb-blocking=off` (a warning rule) → that rule vanishes, + others stay. Correct. +- (c) `rules.module-name-style=on` (a default-off style rule, on a + badly-named module) → it appears where it was silent before. Correct. +- (d) `select=["style"]` + `severity.style=false` → **empty**, i.e. rung 3 + (class switch) applied after rung 2 (select) leaves nothing. Correct — + matches `enabled_rules`'s documented ladder. +- (e) `rules.module-name-style=on` + `ignore=["module-name-style"]` in the + same push → absent. Rung 5 beats rung 4. Correct. +- (f) every key sent explicitly at its default value → identical to the + no-configuration baseline (one publish, same set). Correct. +- A sequential single-session run (default → style off → reset to `{}` → + a rule off) reproduced the same transitions, confirming each + `didChangeConfiguration` payload fully replaces the settings rather than + merging (an empty `{"lint":{}}` genuinely resets every key). +- Diagnostic severities: `wire-reg-mixup` (error) → LSP 1, `always-comb- + blocking` (warning) → LSP 2, `no-tabs` (style) → LSP 3 (INFORMATION). + Confirmed. +- **False start, resolved.** An earlier *interactive* driver (writing one + frame, reading, writing the next) mis-reported scenario (d) as returning + the unchanged baseline set. Cross-checked two ways: a throwaway unit test + in a copy of `settings.rs` calling `from_payload` + `lint::enabled_rules` + directly on the same JSON returned the correct empty set, and the + whole-session driver above (matching `tests/e2e.rs`'s own proven model) + also returned the correct empty set on the real wire. The interactive + script's read/write interleaving was the bug, not the product; recorded + here for the trail, not as a finding. +- Drift test: read `the_vscode_lint_toggles_match_the_registry` + (`crates/lucisv_server/src/settings.rs`). Added a fake rule + (`qa-fake-rule`) to the registry in a throwaway worktree copy (not + `lint-1`) without touching `package.json` — the test **failed**, naming + the mismatch and pointing at the regenerate command. Not a test that + cannot fail. Throwaway worktree removed afterward. + +**4. The 19 new rules, adversarially.** For each rule: a true positive, a +near-miss that must not fire, and a plan-named edge case, via `lucisv check +--select ` on hand-written files. + +*Error class* (false positive here would be HIGH): +- `mismatched-labels`: `end : wrong` fires; matching label, unlabeled `end`, + matching `generate` block label, matching `endclass : name` all silent; + mismatched generate label and mismatched `endclass` label both fire. All + correct, no false positives. +- `duplicate-declaration`: two `logic a;` fires; non-ANSI `input clk;` + + `logic clk;` silent; two `generate` arms each declaring `x` silent; a + macro-expanded double declaration (`` `DECLARE_X`` twice) silent. All + correct. +- `undeclared-identifier` (project only): a genuinely undeclared name in a + project with no wildcard import fires; the same name is silent as a single + file (rule is off without a workspace, confirmed via `--select` on one + file vs. on its directory); a hierarchical tail (`u_sub.internal_sig`), a + `$unit`-scope name declared outside any module and used from another file, + and a name that appears only inside a macro invocation argument are all + silent — none of these produced a false positive. **One thing worth + recording, not a bug**: a file with *any* wildcard package import + (`import p::*;`) gets every otherwise-unresolved value-position name + reclassified from `Resolution::NotFound` to `Resolution::ExternalCandidate` + at the single-file bind stage (`vlog_semantic::resolve::miss`), and the + rule's own doc says it never looks past that — "a package member ... + resolve[s] elsewhere and never reach[es] here." I verified this is + unconditional: a name that is genuinely **not** a member of the + wildcard-imported package still does not fire. This is squarely the + documented, deliberate trade-off ("Error... a rule may only claim it when + it is certain") — most UVM testbenches carry `import uvm_pkg::*;`, so the + rule's real-world reach is narrower than the opentitan "5 findings, all + true" headline number suggests on its own. Not a forcing finding since it + matches the rule's own stated contract exactly; worth a line in the + README's own doc if the lead wants it more visible. +- `unknown-port` / `unknown-parameter`: `.nonexistent_port(clk)` on an + indexed module fires; a correct connection is silent; `.*` is silent; an + interface-typed port (`bus_if.m b`) connected by name is silent; a + parameter override of a `localparam` (`.DOUBLE(16)`) fires as + `unknown-parameter`, matching the dev's stated "counts it as true"; a + module not indexed anywhere (single file, unknown submodule) is silent; a + module indexed **twice** (two files each declaring `module leaf`) is + silent. All eight scenarios matched the plan exactly. + +*Warning class* (false positive here is MEDIUM): `forbid-defparam`, +`invalid-system-task-function`, `truncated-numeric-literal` (fire on +overflow, silent at-width, silent on an all-`z`/`x` literal), +`undersized-binary-literal` (fire on a short literal, silent when full-width, +silent on `4'b0`), `suspicious-semicolon`, `packed-dimensions-range- +ordering`, `module-port` (fires on ≥2 **positional** connections, silent +named, silent single-positional — checked the actual semantics against the +doc after an initial wrong guess), `module-parameter` (same shape), +`explicit-function-task-parameter-type` (fires on an untyped arg, silent +when typed, silent when a later arg shares an earlier one's declared type — +`int a, b` is both `int`), `plusarg-assignment`, `instance-shadowing`, +`forbid-negative-array-dim`, `void-cast` (fires on `void'(x)` around a plain +variable — not around a discarded call result, which is the opposite of my +first guess; silent around a real call; silent around +`randomize(x) with {...}`, the documented false-positive fix), and +`incomplete-assignment` (fires on an `if` with no `else`, silent with an +`else`, silent on a `case` with `default`). All fourteen behaved exactly as +documented; zero false positives, zero missed true positives on the stated +shapes. (Note: TODO §33.3 says "the thirteen listed" but the Measurements +table lists fourteen warning-class rules delivered — a small, harmless +wording/count mismatch, LOW.) + +**5. Opentitan census (read-only).** `lucisv check --output-format json hw` +(3 947 `.sv`/`.v`/`.svh`/`.vh` files by my own glob — close enough to the +dev's 3 975 that the difference is almost certainly extension-set or a file +added/removed since; not investigated further) produced 619 violations. One +file failed to lex (`riscv_core_setting.tpl.sv`, a Jinja template, not real +Verilog — pre-existing, unrelated to this lane) — same as the baseline would +report. Per-rule counts for every §33 rule matched the README's table +**exactly**: `mismatched-labels` 1, `undeclared-identifier` 5, `unknown-port` +40, `unknown-parameter` 4, `invalid-system-task-function` 23, +`undersized-binary-literal` 6, `suspicious-semicolon` 5, +`packed-dimensions-range-ordering` 4, `module-port` 161, +`explicit-function-task-parameter-type` 5, `plusarg-assignment` 13, +`instance-shadowing` 129, and zero for `duplicate-declaration`, +`forbid-defparam`, `truncated-numeric-literal`, `module-parameter`, +`forbid-negative-array-dim`, `void-cast`, `incomplete-assignment`. Read five +each of `undeclared-identifier` (the five `ibex/dv/formal/spec/spec_api.sv` +implicit-net findings, exactly as documented — true), `unknown-port` (five +`pre_dv`/`fpv` testbench-vs-RTL port mismatches — read as true, consistent +with those directories sitting outside `dvsim`'s lint scope) and +`instance-shadowing` (five nested-scope name reuses, e.g. loop variable `i` +and a common `ral`/`id` — plausible warning-class findings, not false +positives, though a few are the kind of "judgment" case the dev's own sample +already flagged). `duplicate-declaration` and `incomplete-assignment`: 0, +matching. `git status --porcelain` in opentitan stayed at the same three +pre-existing files after this run. + +**Timing — MEDIUM finding.** Rebuilt the 0.34.0 baseline (999edd0, byte- +identical to the one the dev used) since the original was gone from `/tmp`. +`lucisv check hw`, interleaved NEW/BASE, best of 3 (plus a separate 5-run +pass for the new binary alone): **new lane ≈ 1.05 s, 0.34.0 baseline ≈ +0.83 s — roughly 25% slower**, on this machine, right now — the opposite of +the dev's reported 0.83 s → 0.91 s... (dev: new *faster* than baseline; here: +new *slower*). `--ignore unknown-port --ignore unknown-parameter` did not +recover much (~0.92 s best of 3), unlike the dev's reported drop to 0.66 s. +This session ran many concurrent cargo builds/tests across several worktrees +throughout the QA pass, which is a real possible confound (shared cache +contention, thermal throttling) — I do not have a quiet machine to rule that +out — but the regression was consistent and reproducible across 11 +interleaved measurements, not a one-off. Flagging as MEDIUM per the timing +threshold; recommend the dev or lead re-measure on an otherwise-idle machine +before treating the absolute numbers as settled. This does not affect +correctness and is not a PASS blocker on its own. + +**6. `Semantics::duplicates()`.** `git diff 965c4ee -- crates/vlog_semantic/ +src/facts.rs`: empty — no `FACTS_FORMAT` change. Reviewed the `bind/mod.rs`, +`model.rs` and `lib.rs` diffs directly: the "already bound" arm in +`declare()` now also pushes a `Duplicate` record before doing exactly what it +did before (`use_name` + return `None`); nothing else in that function +changed. `cargo test -p vlog_semantic` in a throwaway worktree at 965c4ee vs. +in `lint-1`: **test-for-test identical** (17 binaries, same pass count in +each, e.g. 31/12/27/13/1/12/3/8/26+1ignored/40+1ignored/31/32/18/9/5/86+2ignored/0). +Corpus, 17-original-rules-only: ran both the new binary and the rebuilt +baseline with the **same explicit** `--select ` +over all 860 corpus files and diffed the JSON (severity field stripped for +the comparison) — **0 differing**. (First attempt at this compared the new +binary's explicit `--select` output against the *baseline's own default* +run and found 13 spurious diffs, all `undriven-net`/`unused-signal` — +these are `needs_workspace`-gated, default-off-without-a-project rules, and +an explicit `--select` bypasses that gate in both versions identically per +`select_rules`'s documented contract; comparing against the baseline's +unselected default was an apples-to-oranges mistake on my part, not a +product issue — resolved by selecting the same list on both sides.) + +**7. Docs.** `--rules-doc`'s 36 rule names/severities match README.md's +36-row table exactly, and match the docs-site +`reference/rules.md`'s 36 section headers exactly (diffed all three sets +programmatically). `editors/vscode/README.md` documents the tri-state +dropdown (`default`/`on`/`off`) and spells out the five-rung precedence +ladder in prose (does not use the literal words "tri-state"/"rung", but the +content is there and correct). TODO.md §33 checkboxes match the work done; +only the QA line is (correctly) still unchecked. **LOW**: the dev's work log +does not record the "`docs/site/dist` was not rebuilt" note the plan +expected — independently confirmed true (`git diff --name-only 965c4ee -- +docs/site/dist` is empty) but not written down anywhere in the feature +README. **LOW**: §33.3's TODO text says "the thirteen listed" against +fourteen warning rules actually delivered (see §4 above) — cosmetic. + +**Verdict: PASS.** + +No HIGH or CRITICAL findings. Every Error-class rule was attacked with the +plan's own named shapes and produced zero false positives; the drift test +provably fails when it should; the precedence ladder is correct on the real +wire; the 17 original rules are byte-identical to baseline; opentitan is +untouched. Two LOW documentation nits and one MEDIUM timing measurement +(reproducible on this machine, opposite sign from the dev's own numbers, +confounded by heavy concurrent build load during this QA pass) are recorded +above for the lead's attention; none of them are correctness or safety-net +issues and none block merge on their own. + +## Review + +**2026-09-03 — lead.** Accepted. The round is larger than any linter +change before it — 17 → 36 rules, a severity on every one, the editor +surface generated from the registry — and its discipline held: each +rule is its own file with true positives and near-misses, the +false-positive classes found on opentitan were closed one test at a +time (456 → 6 on `undersized-binary-literal` by matching Verible's +`lint_zero` default; 94 → 5 on `undeclared-identifier` by giving an +`` `include``d fragment no opinion), and the drift test was proved able +to fail. Two decisions the plan did not make are the right ones: the +per-rule setting is tri-state because a VS Code client sends every key +at its default and a boolean cannot say "unset" — the plan's boolean +would have silently overridden `select` and the class switches for +every user; and `undeclared-identifier` ships on-with-a-project because +its unexplained count is zero and its silence rule (any other file +mentioning the name) is the false-negative-safe direction the semantic +lints already use. The two handshakes taken (`Semantics::duplicates()`, +additive, no store change; two lines in `notification.rs` so a toggle +republishes) are accepted. QA's MEDIUM timing note was measured under +another lane's compiles; re-measured at merge on a quiet machine and +recorded below. Ships in 0.36.0. Wave 2 (§34) takes the Style family +and per-rule options. diff --git a/docs/site/src/content/docs/reference/rules.md b/docs/site/src/content/docs/reference/rules.md index 2bbe82f..9784af7 100644 --- a/docs/site/src/content/docs/reference/rules.md +++ b/docs/site/src/content/docs/reference/rules.md @@ -1,31 +1,56 @@ --- title: Lint rules -description: Complete reference for all seventeen lucisv lint rules, their defaults, fixes, and rationale. +description: Complete reference for every lucisv lint rule, its severity, default, fix, and rationale. --- -17 rules indexed +36 rules indexed + +Every rule is in one of three **severity** classes. `error` is code that would very likely fail to compile, elaborate or synthesize; `warning` is code that compiles and very likely does not mean what it says; `style` is code that is correct and reads badly. The class is the word in the CLI diagnostic line (`FILE:LINE:COL: warning: …`), the `severity` field of `--output-format json`, and the colour of the editor's squiggle — and it is accepted wherever a rule name is, so `--ignore style` and `--select error` both work. + +Every `error`-class rule is held to one discipline: it goes **silent whenever the run cannot answer** — a file that did not fully parse, a module the project does not hold or holds twice, a name a macro produces, a fragment written to be `` `include``d. A wrong accusation in that class is worse than a hundred missed ones. + +This page is hand-written prose. The generated truth is `lucisv check --rules-doc`, which prints every rule with its class, default, fix and rationale straight from the registry. A rule marked **on (project)** runs by default only where lucisv can see the other files of your project — `lucisv check `, or the language server. Over a single file or a stdin buffer it is off and must be `--select`ed, because its one false-positive mode is a use in another file. Turn any rule off with `--ignore`, with `ignore` under `[lint]` in `lucisv.toml`, or with `lucisv.lint.ignore` in your editor. -| Rule | Default | Fix | Purpose | -|---|:---:|:---:|---| -| [`always-comb-blocking`](#always-comb-blocking) | on | — | Use `=` inside `always_comb` | -| [`always-ff-non-blocking`](#always-ff-non-blocking) | on | — | Use `<=` inside `always_ff` | -| [`case-missing-default`](#case-missing-default) | on | — | Give every case a default branch | -| [`empty-item`](#empty-item) | on | safe | Drop a `;` that stands where an item belongs | -| [`enum-name-style`](#enum-name-style) | on | — | Name enum typedefs with `_e` or `_t` | -| [`explicit-parameter-storage-type`](#explicit-parameter-storage-type) | on | — | Declare parameter storage types | -| [`module-filename`](#module-filename) | on | — | Match one-module files to module names | -| [`module-name-style`](#module-name-style) | off | — | Use lower_snake_case module names | -| [`multiply-driven`](#multiply-driven) | on (project) | — | Give variables one driver | -| [`no-tabs`](#no-tabs) | on | safe | Use spaces outside string literals | -| [`no-trailing-whitespace`](#no-trailing-whitespace) | on | safe | Remove end-of-line whitespace | -| [`parameter-name-style`](#parameter-name-style) | on | — | Use CamelCase or ALL_CAPS parameters | -| [`struct-union-name-style`](#struct-union-name-style) | on | — | Name aggregate typedefs with `_t` | -| [`undriven-net`](#undriven-net) | on (project) | — | Drive signals that are read | -| [`unused-signal`](#unused-signal) | on (project) | — | Detect unreferenced internal signals | -| [`unused-waiver`](#unused-waiver) | on | — | Remove ineffective suppressions | -| [`wire-reg-mixup`](#wire-reg-mixup) | on | — | Prefer `logic` to `reg` in SystemVerilog | +| Rule | Severity | Default | Fix | Purpose | +|---|:---:|:---:|:---:|---| +| [`always-comb-blocking`](#always-comb-blocking) | warning | on | — | Use `=` inside `always_comb` | +| [`always-ff-non-blocking`](#always-ff-non-blocking) | warning | on | — | Use `<=` inside `always_ff` | +| [`case-missing-default`](#case-missing-default) | warning | on | — | Give every case a default branch | +| [`duplicate-declaration`](#duplicate-declaration) | error | on | — | Declare each name once per scope | +| [`empty-item`](#empty-item) | style | on | safe | Drop a `;` that stands where an item belongs | +| [`enum-name-style`](#enum-name-style) | style | on | — | Name enum typedefs with `_e` or `_t` | +| [`explicit-function-task-parameter-type`](#explicit-function-task-parameter-type) | warning | on | — | Type every function and task argument | +| [`explicit-parameter-storage-type`](#explicit-parameter-storage-type) | style | on | — | Declare parameter storage types | +| [`forbid-defparam`](#forbid-defparam) | warning | on | — | Override at the instantiation, not with `defparam` | +| [`forbid-negative-array-dim`](#forbid-negative-array-dim) | warning | on | — | Keep negative literals out of dimensions | +| [`incomplete-assignment`](#incomplete-assignment) | warning | on | — | Assign on every path of an `always_comb` | +| [`instance-shadowing`](#instance-shadowing) | warning | on | — | Do not hide an enclosing declaration | +| [`invalid-system-task-function`](#invalid-system-task-function) | warning | on | — | Avoid deprecated and non-reproducible system tasks | +| [`mismatched-labels`](#mismatched-labels) | error | on | — | Make an end label name its own block | +| [`module-filename`](#module-filename) | style | on | — | Match one-module files to module names | +| [`module-name-style`](#module-name-style) | style | off | — | Use lower_snake_case module names | +| [`module-parameter`](#module-parameter) | warning | on | — | Override more than one parameter by name | +| [`module-port`](#module-port) | warning | on | — | Connect more than one port by name | +| [`multiply-driven`](#multiply-driven) | error | on (project) | — | Give variables one driver | +| [`no-tabs`](#no-tabs) | style | on | safe | Use spaces outside string literals | +| [`no-trailing-whitespace`](#no-trailing-whitespace) | style | on | safe | Remove end-of-line whitespace | +| [`packed-dimensions-range-ordering`](#packed-dimensions-range-ordering) | warning | on | — | Write a packed dimension `[N-1:0]` | +| [`parameter-name-style`](#parameter-name-style) | style | on | — | Use CamelCase or ALL_CAPS parameters | +| [`plusarg-assignment`](#plusarg-assignment) | warning | on | — | Read a plusarg with `$value$plusargs` | +| [`struct-union-name-style`](#struct-union-name-style) | style | on | — | Name aggregate typedefs with `_t` | +| [`suspicious-semicolon`](#suspicious-semicolon) | warning | on | — | No `if (x);` or `while (x);` | +| [`truncated-numeric-literal`](#truncated-numeric-literal) | warning | on | — | Keep a sized literal inside its width | +| [`undeclared-identifier`](#undeclared-identifier) | error | on (project) | — | Use a name something declares | +| [`undersized-binary-literal`](#undersized-binary-literal) | warning | on | safe | Write every bit of a sized binary literal | +| [`undriven-net`](#undriven-net) | warning | on (project) | — | Drive signals that are read | +| [`unknown-parameter`](#unknown-parameter) | error | on (project) | — | Override only parameters the module declares | +| [`unknown-port`](#unknown-port) | error | on (project) | — | Connect only ports the module declares | +| [`unused-signal`](#unused-signal) | warning | on (project) | — | Detect unreferenced internal signals | +| [`unused-waiver`](#unused-waiver) | style | on | — | Remove ineffective suppressions | +| [`void-cast`](#void-cast) | warning | on | — | Cast to `void` only what a call returns | +| [`wire-reg-mixup`](#wire-reg-mixup) | error | on | — | Prefer `logic` to `reg` in SystemVerilog | ## always-comb-blocking @@ -94,3 +119,79 @@ Reports malformed, unknown, or ineffective waiver comments when their target rul ## wire-reg-mixup Reports `reg` in `.sv` and `.svh` files and recommends `logic`. Verilog `.v`/`.vh` files and unnamed stdin are exempt; `wire` remains valid and is never flagged. + +## duplicate-declaration + +Reports a name a scope binds twice — two signals, two parameters, two typedefs, two instances. It is silent whenever the second declaration might be legal: a **port** on either side (a non-ANSI port is completed by its body declarations, all legally), a function, task, class, constraint, covergroup, property, sequence, modport or clocking name (each has a prototype-plus-definition or forward-declaration form), an enum **name range** (`Gpr[0:2]` declares a run of members under one written identifier), a `generate` scope, a pair separated by a conditional-compilation directive, the file scope, and any file that did not fully parse. Measured on opentitan: 18 findings before those exclusions, all of them phantoms from one 454-error UVM file, and 0 after. + +## explicit-function-task-parameter-type + +Reports a task or function formal with no storage type, which the language makes a one-bit `logic` (IEEE 1800 §13.3). Only the argument that *opens* a declaration is judged — a continuation (`f(input int a, b)`) inherits — and a DPI import's unnamed formal is not this rule's subject. Verible's `explicit-function-task-parameter-type`, same default. + +## forbid-defparam + +Reports `defparam`, deprecated since IEEE 1800-2009 and rejected outright by several synthesis tools. The `#(.NAME(value))` override at the instantiation says the same thing where the instance is. Verible's `forbid-defparam`, same default. + +## forbid-negative-array-dim + +Reports a written negative literal inside a dimension, packed or unpacked — the shape `[WIDTH-1:0]` collapses to when `WIDTH` comes out zero. Only a literal is judged; an expression that would evaluate negative needs parameter values lucisv does not have. Verible ships this off; lucisv turns it on, because a negative literal spelled out in a dimension has no legitimate reading. + +## incomplete-assignment + +Reports a variable an `always_comb` writes under an `if` with no `else`, or in some arms of a `default`-less `case`, and nowhere unconditionally before — a latch inferred where none was wanted. Conservative by construction: it reads only the top level of the block, treats a partial write and an every-arm `if`/`else` or `case` as coverage, and never reports a name the block declares for itself. No Verible equivalent. Measured on opentitan: 3 findings before those exclusions, all false, 0 after; 3 on lucisv's corpus, all real latches in `common_cells/src/deprecated`. + +## instance-shadowing + +Reports a declaration that hides one from an enclosing scope of the same design unit — the block-local `count` that quietly changes what every `count` in the block means. Only data and instances are judged (a subroutine argument named after a signal is idiomatic), and only within one unit. Verible ships this off; lucisv turns it on. + +## invalid-system-task-function + +Reports `$random`, `$srandom`, the `$dist_*` family and `$psprintf`, and names the replacement. The random family all draw from one global generator, so a call added anywhere reshuffles every other stream and a failing seed stops reproducing; `$psprintf` is a vendor spelling of `$sformatf`. Verible's `invalid-system-task-function`, same list, same default. + +## mismatched-labels + +Reports an end label that does not name the block it closes, and an `end : name` on a block that has none — both compile errors (IEEE 1800 §9.3.4). Every construct that may carry a footer label is checked with one answer: module, interface, program, package, class, function, task, `begin`, `fork`/`join`, generate block, clocking block, covergroup, property and sequence. Verible ships this off; lucisv turns it on and files it as an error. + +## module-parameter + +Reports more than one positional parameter override, which binds by order and silently changes what every instance elaborates to when a parameter is added or two are swapped. Verible's `module-parameter`, same default. + +## module-port + +Reports more than one positional port connection, for the same reason. A single-port instance has no order to get wrong and is left alone. Verible's `module-port`, same default. + +## packed-dimensions-range-ordering + +Reports a packed dimension that counts upwards (`[0:7]`, `[0:WIDTH-1]`), where bit 0 is the most significant one and every concatenation with an ordinary `[7:0]` vector silently reverses. Unpacked arrays are not judged — an ascending array is normal — and two symbolic bounds lucisv cannot compare are left alone. Verible's `packed-dimensions-range-ordering`, same default. + +## plusarg-assignment + +Reports `$test$plusargs`, which matches by *prefix* — `+foobar` makes `$test$plusargs("foo")` true — and asks for `$value$plusargs`, which matches the whole name and hands back the value. Verible's `plusarg-assignment`, same default. + +## suspicious-semicolon + +Reports `if (x);`, `for (…);`, `while (…);` and their relatives, where the `;` is the whole body and whatever is indented under it runs unconditionally. A deliberately empty body is `begin end` and is not reported. Verible ships this off; lucisv turns it on, because the finding is a typo rather than a matter of taste. + +## truncated-numeric-literal + +Reports a sized literal whose digits need more bits than it declares (`4'hFFF`), which most simulators truncate silently. Leading zeros do not count, and a literal whose digits are all `x`/`z` (`3'hz`) is left alone — those spell an unknown of that width. Verible's `truncated-numeric-literal`, same default. + +## undeclared-identifier + +Reports a name this file does not declare, that no external unit it names could supply, and that **no other file in the project writes down at all**. Every clause is an exclusion, and they are what make an error-class rule about names safe: no project behind the run means no opinion, and so do a name any macro, directive or attribute in the file writes down, a file that did not fully parse, and an `` `include``d fragment with no unit of its own. Measured on opentitan `hw/` and on lucisv's corpus: the same five findings, all real implicit nets in one ibex formal file. No Verible equivalent. + +## undersized-binary-literal + +Reports a sized binary literal that writes fewer digits than its width (`8'b1`), and its safe fix writes the extension the language would have applied — `0` for a literal starting with `0` or `1`, the unknown itself for one starting with `x` or `z`. A literal whose value is zero is exempt, matching Verible's `lint_zero` default. Verible's `undersized-binary-literal`, same bases, same defaults. + +## unknown-parameter + +Reports a `#(.NAME(…))` override naming a parameter the instantiated module does not declare — including a `localparam`, which is not overridable at all. It is silent whenever the project cannot answer: no project, an unindexed module, one declared twice with different headers, one whose header carries a compiler directive, a scope-qualified instantiation. Measured on opentitan: 4 findings, spot-checked true. No Verible equivalent. + +## unknown-port + +Reports a `.name(…)` connection naming a port the instantiated module does not declare — the port rename that reached three of four instantiations. Same silences as `unknown-parameter`; `.*` names nothing and is not judged. Measured on opentitan: 40 findings, spot-checked true, all in pre-silicon testbenches out of step with their RTL. No Verible equivalent. + +## void-cast + +Reports `void'(…)` around something that is not a call, where there is no return value to discard — the missing call, or the cast left over from an edit. Verible's `void-cast` forbids a *named list* of calls instead, so the two do not overlap; the named-call form is wave 2's business. Only a cast standing as a statement is judged. diff --git a/editors/vscode/README.md b/editors/vscode/README.md index f86dafd..70e0183 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -113,6 +113,8 @@ enabling both paths formats twice. |---|---| | Live parse diagnostics | Error-tolerant parsing keeps useful feedback flowing while code is half typed | | Live lint diagnostics | The same lint registry as `lucisv check`, delivered through push or modern pull diagnostics | +| Severity per rule | Every rule is `error`, `warning` or `style`, and the squiggle is painted red, yellow or blue to match | +| Per-rule toggles | One setting per rule and one per severity class, all under `lucisv.lint.*`; changing any of them re-checks every open file immediately | | Safe quick fixes | One lightbulb action per safe lint fix, plus **Fix all lucisv auto-fixable problems** | | Waivers | `lucisv:` and Verible-compatible `verilog_lint:` line/range waivers are understood | | Scope feedback | An unmatched `begin`/`end` or `fork`/`join` is colored as an error until its pair exists | @@ -279,13 +281,29 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`, | `lucisv.index.persist` | `true` | Remember what indexing each file found, so a reopen resumes instead of rescanning | | `lucisv.index.cachePath` | `""` | Where that store lives; empty means the extension's own per-workspace storage folder | | `lucisv.largeFile.threshold` | `4 MiB` | Size in bytes above which an opened file gets viewport-only highlighting and nothing else — no parsing, diagnostics, formatting, or indexing; `0` analyzes everything | +| `lucisv.lint.severity.error` | `true` | Run the rules for code that would very likely not compile; off silences the whole class | +| `lucisv.lint.severity.warning` | `true` | Run the rules for code that compiles and very likely does not mean what it says | +| `lucisv.lint.severity.style` | `true` | Run the rules for code that is correct and reads badly | +| `lucisv.lint.rules.` | `default` | One dropdown per rule — `default`, `on` or `off`. `default` is what the rule ships as, which the setting's own description names | +| `lucisv.lint.select` | `[]` | Power-user spelling of `lucisv check --select`: run exactly these rules, replacing the default set. A severity word (`error`, `warning`, `style`) stands for its whole class | +| `lucisv.lint.ignore` | `[]` | Power-user spelling of `--ignore`, and the off switch of last resort; takes a severity word too | | `lucisv.formatOnSave` | `false` | Protocol save hook for editors without native format-on-save; keep off in VS Code. Its indent comes from `lucisv.toml` or `lucisv.indent`, never from the editor tab size, which the protocol does not send on this path | | `lucisv.serverPath` | bundled | Explicit server override for advanced use; an unchanged setting uses the bundled server | | `lucisv.verbose` | `false` | Print how long every operation took in the lucisv output channel — one `timing:` line per request, notification, scan, widen, buffer flush, and per request that had to wait behind a rescan. **Restarts the language server when changed**, because it is an argument the server is started with | The six `lucisv.index.*` settings and `lucisv.largeFile.threshold` arrive with the [large workspaces](#large-workspaces) work; everything else ships in -0.10.2. +0.10.2. The `lucisv.lint.*` settings are **generated from the rule registry**, +so a rule cannot ship without its toggle. + +When several of them disagree, this is the order — each step may undo the one +above it: + +1. what the rules themselves ship as (a project-wide rule needs a workspace); +2. a non-empty `lucisv.lint.select` replaces that set; +3. a severity switch that is off removes its whole class; +4. a per-rule dropdown set to `on` or `off` decides that one rule; +5. `lucisv.lint.ignore` removes, whatever anything else said. A nearby `lucisv.toml` is the project source of truth and wins over editor style settings. Each file discovers configuration upward, so one workspace may diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 6137cb0..d33a7d5 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -348,6 +348,456 @@ }, "default": [], "markdownDescription": "Lint rules to drop from whatever `#lucisv.lint.select#` left — the editor's spelling of `lucisv check --ignore`. This is the off switch for the three rules that read the whole project rather than one file (`unused-signal`, `undriven-net`, `multiply-driven`): they are on by default wherever lucisv can see the other files of your workspace, because it can then tell that another file reads a signal through a hierarchical path. A name lucisv does not know is ignored. Takes effect immediately — every open file is re-checked." + }, + "lucisv.lint.severity.error": { + "type": "boolean", + "default": true, + "order": 10, + "markdownDescription": "Run the **error** lint rules — code that would very likely fail to compile, elaborate or synthesize. Turning this off silences the whole class; a per-rule toggle below still has the last word, and `#lucisv.lint.ignore#` still removes a rule whatever else says. Takes effect immediately — every open file is re-checked." + }, + "lucisv.lint.severity.warning": { + "type": "boolean", + "default": true, + "order": 11, + "markdownDescription": "Run the **warning** lint rules — code that compiles but very likely does not mean what it says. Turning this off silences the whole class; a per-rule toggle below still has the last word, and `#lucisv.lint.ignore#` still removes a rule whatever else says. Takes effect immediately — every open file is re-checked." + }, + "lucisv.lint.severity.style": { + "type": "boolean", + "default": true, + "order": 12, + "markdownDescription": "Run the **style** lint rules — code that is correct and reads badly. Turning this off silences the whole class; a per-rule toggle below still has the last word, and `#lucisv.lint.ignore#` still removes a rule whatever else says. Takes effect immediately — every open file is re-checked." + }, + "lucisv.lint.rules.duplicate-declaration": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 20, + "markdownDescription": "**error** — declare each name once per scope. On by default." + }, + "lucisv.lint.rules.mismatched-labels": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 21, + "markdownDescription": "**error** — make an end label name the block it closes. On by default." + }, + "lucisv.lint.rules.multiply-driven": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On where lucisv can see the project.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 22, + "markdownDescription": "**error** — give a variable exactly one driver. On where lucisv can see the project." + }, + "lucisv.lint.rules.undeclared-identifier": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On where lucisv can see the project.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 23, + "markdownDescription": "**error** — use a name something declares. On where lucisv can see the project." + }, + "lucisv.lint.rules.unknown-parameter": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On where lucisv can see the project.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 24, + "markdownDescription": "**error** — override only parameters the instantiated module declares. On where lucisv can see the project." + }, + "lucisv.lint.rules.unknown-port": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On where lucisv can see the project.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 25, + "markdownDescription": "**error** — connect only ports the instantiated module declares. On where lucisv can see the project." + }, + "lucisv.lint.rules.wire-reg-mixup": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 26, + "markdownDescription": "**error** — use `logic` instead of `reg` in SystemVerilog files. On by default." + }, + "lucisv.lint.rules.always-comb-blocking": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 27, + "markdownDescription": "**warning** — assign with `=` inside always_comb. On by default." + }, + "lucisv.lint.rules.always-ff-non-blocking": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 28, + "markdownDescription": "**warning** — assign with `<=` inside always_ff. On by default." + }, + "lucisv.lint.rules.case-missing-default": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 29, + "markdownDescription": "**warning** — give every case statement a default branch. On by default." + }, + "lucisv.lint.rules.explicit-function-task-parameter-type": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 30, + "markdownDescription": "**warning** — declare a storage type on every function and task argument. On by default." + }, + "lucisv.lint.rules.forbid-defparam": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 31, + "markdownDescription": "**warning** — override a parameter at the instantiation, not with `defparam`. On by default." + }, + "lucisv.lint.rules.forbid-negative-array-dim": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 32, + "markdownDescription": "**warning** — do not write a negative constant in a dimension. On by default." + }, + "lucisv.lint.rules.incomplete-assignment": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 33, + "markdownDescription": "**warning** — assign every variable on every path of an always_comb. On by default." + }, + "lucisv.lint.rules.instance-shadowing": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 34, + "markdownDescription": "**warning** — do not hide an enclosing declaration with a new one of the same name. On by default." + }, + "lucisv.lint.rules.invalid-system-task-function": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 35, + "markdownDescription": "**warning** — do not call a deprecated or non-reproducible system task. On by default." + }, + "lucisv.lint.rules.module-parameter": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 36, + "markdownDescription": "**warning** — override more than one parameter by name. On by default." + }, + "lucisv.lint.rules.module-port": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 37, + "markdownDescription": "**warning** — connect an instance with more than one port by name. On by default." + }, + "lucisv.lint.rules.packed-dimensions-range-ordering": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 38, + "markdownDescription": "**warning** — declare a packed dimension in decreasing order, `[N-1:0]`. On by default." + }, + "lucisv.lint.rules.plusarg-assignment": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 39, + "markdownDescription": "**warning** — read a plusarg with `$value$plusargs`, not `$test$plusargs`. On by default." + }, + "lucisv.lint.rules.suspicious-semicolon": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 40, + "markdownDescription": "**warning** — do not end a control statement's header with a `;`. On by default." + }, + "lucisv.lint.rules.truncated-numeric-literal": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 41, + "markdownDescription": "**warning** — keep a sized literal inside the width it declares. On by default." + }, + "lucisv.lint.rules.undersized-binary-literal": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 42, + "markdownDescription": "**warning** — write every bit of a sized binary literal. On by default." + }, + "lucisv.lint.rules.undriven-net": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On where lucisv can see the project.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 43, + "markdownDescription": "**warning** — drive a signal that something reads. On where lucisv can see the project." + }, + "lucisv.lint.rules.unused-signal": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On where lucisv can see the project.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 44, + "markdownDescription": "**warning** — delete a signal nothing uses. On where lucisv can see the project." + }, + "lucisv.lint.rules.void-cast": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 45, + "markdownDescription": "**warning** — cast to `void` only what a call returns. On by default." + }, + "lucisv.lint.rules.empty-item": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 46, + "markdownDescription": "**style** — drop a `;` that stands where an item belongs. On by default." + }, + "lucisv.lint.rules.enum-name-style": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 47, + "markdownDescription": "**style** — name enum typedefs in lower_snake_case ending in _e or _t. On by default." + }, + "lucisv.lint.rules.explicit-parameter-storage-type": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 48, + "markdownDescription": "**style** — declare a storage type on every parameter. On by default." + }, + "lucisv.lint.rules.module-filename": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 49, + "markdownDescription": "**style** — name a one-module file after its module. On by default." + }, + "lucisv.lint.rules.module-name-style": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: Off by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 50, + "markdownDescription": "**style** — name modules in lower_snake_case. Off by default." + }, + "lucisv.lint.rules.no-tabs": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 51, + "markdownDescription": "**style** — use spaces, not tabs. On by default." + }, + "lucisv.lint.rules.no-trailing-whitespace": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 52, + "markdownDescription": "**style** — no whitespace at the end of a line. On by default." + }, + "lucisv.lint.rules.parameter-name-style": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 53, + "markdownDescription": "**style** — name parameters in CamelCase or ALL_CAPS. On by default." + }, + "lucisv.lint.rules.struct-union-name-style": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 54, + "markdownDescription": "**style** — name struct and union typedefs in lower_snake_case ending in _t. On by default." + }, + "lucisv.lint.rules.unused-waiver": { + "type": "string", + "enum": ["default", "on", "off"], + "enumDescriptions": [ + "Leave it as it ships: On by default.", + "Always run this rule.", + "Never run this rule." + ], + "default": "default", + "order": 55, + "markdownDescription": "**style** — remove waivers that no longer suppress anything. On by default." } } }