Merge branch 'lint-2'

This commit is contained in:
lucio committed 2026-09-04 03:36:59 -05:00
commit 17697b9d77
59 files changed
+7298 -158

No files matched your search

+86 -2
View File
@@ -251,6 +251,24 @@ makes an editor's red squiggle worth believing.
| `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) |
| `line-length` | style | — | no line wider than the width the formatter uses |
| `posix-eof` | style | safe | the file ends with a newline |
| `forbid-consecutive-null-statements` | style | safe | no `;;` where a statement belongs |
| `generate-label` | style | — | every generate block carries a `: label` |
| `generate-label-prefix` | style | — | that label starts with `g_` or `gen_` |
| `package-filename` | style | — | a one-package file is named after its package |
| `interface-name-style` | style | — | `lower_snake_case` ending `_if` |
| `macro-name-style` | style | — | a `` `define`` name is `ALL_CAPS` |
| `constraint-name-style` | style | — | `lower_snake_case` ending `_c` |
| `typedef-enums` | style | — | an `enum` type is named with a `typedef` |
| `typedef-structs-unions` | style | — | a `struct`/`union` type is named with a `typedef` |
| `always-comb` | style | unsafe | `always_comb`, not `always @*` |
| `signal-name-style` | style | — | `lower_snake_case` signals (off by default) |
| `parameter-type-name-style` | style | — | `lower_snake_case` ending `_t` type parameters (off) |
| `port-name-suffix` | style | — | `_i` / `_o` / `_io` say which way a port points (off) |
| `one-module-per-file` | style | — | one `module` per file (off by default) |
| `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) |
| `explicit-begin` | style | safe | every body is a `begin ... end` block (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
@@ -266,11 +284,77 @@ 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
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
that cannot change what the code means), `--unsafe-fixes` widens that to the
rest. One rule ships an unsafe fix: `always-comb` rewrites `always @*` to
`always_comb`, which is a different block at time zero and makes a second
driver of its outputs an error — right nearly always, and not lucisv's call to
make without being asked. Violations inside a `// verilog_format: off`
region are reported but never fixed: `off` means hands-off for the linter too,
so `--fix` leaves every byte of a fenced region exactly as written.
### Rule options
A rule can be configured in a `[lint.<rule-name>]` table:
```toml
[lint]
ignore = ["typedef-structs-unions"]
[lint.line-length]
length = 120 # the linter's limit, if not the formatter's
[lint.generate-label-prefix]
prefix = ["g_", "gen_"] # the label prefixes this project writes
[lint.parameter-name-style]
localparam_style = "CamelCase" # Verible's own default, stricter than ours
[lint.signal-name-style]
style_regex = "[a-z][a-z_0-9]*" # a pattern, matched against the whole name
```
The keys are Verible's wherever it has the same option, so a `.rules.verible`
file translates word for word. An option nobody sets reads the default
`lucisv check --rules-doc` prints beside it. An unknown rule or option name, a
value of the wrong kind, an integer out of range or a pattern that does not
compile **fails the run**, naming the config file and the line — a typo in a
lint setting is not something to guess at.
Patterns are not full RE2. What is supported: literals, `.`, `[...]` classes
with ranges and negation, the escapes `\d \D \w \W \s \S` (character
classes), `\n \t \r` (control characters) and `\<punctuation>` (that
character, literally), groups, `|`, and the postfix `*` `+` `?` — matched
against the **whole** name, so `^`/`$` are accepted and redundant.
Everything else is **refused when the option is read, by name**: counted
repetition (`{2,3}`), lookaround and flag groups (`(?=…)`, `(?:…)`), and every
escape not listed above — a backreference (`\1`), a word boundary (`\b`),
`\A`, `\z`, `\p{…}`, `\x41`. An unsupported escape read as a literal would
quietly judge the wrong names (`\bword\b` would match `bwordb`), which is
worse than an error you can read.
Matching is a Thompson-NFA simulation, so it is linear in pattern × name
length whatever shape the pattern has: no pattern can make `lucisv check` — or
an editor session — hang.
From an editor the same options are one object, `lucisv.lint.options`:
```json
"lucisv.lint.options": {
"line-length": { "length": 120 },
"typedef-structs-unions": { "allow_anonymous_nested": false }
}
```
There the precedence is **the editor's value, then the `lucisv.toml`, then the
rule's default — key by key**: a project can set two options and one user
override the third without losing the others. (This is the opposite order to
the formatting settings, where a checked-in `lucisv.toml` outranks the editor:
formatting has a byte-exact contract with CI, and which findings you are shown
in your own editor is yours to choose.) A bad entry there is *ignored* and
reported in the lucisv log rather than fatal, so one typo cannot leave a
session with no diagnostics.
### Waivers
```systemverilog
+5 -5
View File
@@ -3764,14 +3764,14 @@ README.md}, README.md "Linting", docs/site/.../reference/rules.md,
docs/features/linter-expansion-2/README.md (new), TODO §34. Worktree
`lint-2`; disjoint from §32 (parser) so the two may run in parallel.
Every suite and sweep under `tools/guard.sh`.
- [ ] 34.0 options end to end (spec, validation, toml table, editor
- [x] 34.0 options end to end (spec, validation, toml table, editor
object, precedence, --rules-doc); pins
- [ ] 34.1 options on the four existing naming rules; defaults
- [x] 34.1 options on the four existing naming rules; defaults
byte-identical
- [ ] 34.2 the eighteen Style rules, each with tests, counts and ten
- [x] 34.2 the eighteen Style rules, each with tests, counts and ten
classified findings
- [ ] 34.3 docs + regenerated toggles
- [ ] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
- [x] 34.3 docs + regenerated toggles
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
814/820 byte-identical; vsix smoke; opentitan read-only census +
timing vs 0.36.0
- [ ] QA: options attacked (bad key/kind/range/regex on both front
+52 -10
View File
@@ -14,7 +14,9 @@ use rayon::prelude::*;
use vlog_formatter::fence::{self, Region};
use vlog_formatter::Config;
use vlog_linter::words;
use vlog_linter::{apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, Violation};
use vlog_linter::{
apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, RuleOptions, Violation,
};
use vlog_parser::LineIndex;
use crate::args::{Options, OutputFormat};
@@ -31,6 +33,9 @@ pub struct Job {
path: PathBuf,
config: Config,
rules: Vec<&'static dyn Rule>,
/// What this file's `lucisv.toml` configured about each rule, validated
/// against the registry when the run was planned.
options: RuleOptions,
}
/// A whole `lucisv check` run: what to lint, and what the project says about
@@ -163,7 +168,8 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
let rules = vlog_linter::select_rules(select, ignore, workspace)
.map_err(|e| format!("{}: {e}", path.display()))?;
jobs.push(Job { path, config, rules });
let options = rule_options(&file_config)?;
jobs.push(Job { path, config, rules, options });
}
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule)));
@@ -171,6 +177,30 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
Ok(Plan { jobs, census })
}
/// The `[lint.<rule>]` entries of one file's config, resolved against the
/// registry.
///
/// The names and the values are checked **here**, where the registry is, and
/// the first bad entry fails the run naming the config file and the line it
/// was written on — the same treatment a bad `[lint] select` name gets, and
/// for the same reason: a user typed it and is watching.
pub fn rule_options(file_config: &FileConfig) -> Result<RuleOptions, String> {
let mut options = RuleOptions::new();
for entry in &file_config.lint_options {
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
let file = file_config
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
// The rule is named as well as the option: the table header two
// lines up says which rule it is, and an error a user reads out
// of a CI log has no table header beside it.
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
})?;
}
Ok(options)
}
/// Whether this rule reads the census's **interface** half, which costs a
/// parse of every file in the run rather than a lex.
///
@@ -215,7 +245,9 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
let mut reports: Vec<Report> = plan
.jobs
.par_iter()
.map(|job| check_one(&job.path, &job.config, opts, &job.rules, plan.census.as_ref()))
.map(|job| {
check_one(&job.path, &job.config, opts, &job.rules, &job.options, plan.census.as_ref())
})
.collect();
// Diagnostics are printed sorted by path, then by position within the
// file (`lint` already sorts those), so a run over a directory reads
@@ -231,10 +263,11 @@ pub fn check_stdin(
src: &str,
config: &Config,
rules: &[&'static dyn Rule],
options: &RuleOptions,
) -> ExitCode {
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
let (violations, lex_error) = run_rules(src, path, config, rules, None);
let (violations, lex_error) = run_rules(src, path, config, rules, options, None);
// Nothing is ever written back for stdin, so `--fix` has nothing to do
// here; the violations are reported as they are.
let error = lex_error.map(|e| format!("{name}: {e}"));
@@ -248,6 +281,7 @@ fn check_one(
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
options: &RuleOptions,
census: Option<&Census>,
) -> Report {
let path = file.display().to_string();
@@ -265,10 +299,10 @@ fn check_one(
};
let outcome = crate::catch_panic(|| {
if opts.fix {
fix_source(&src, file, config, opts, rules, census)
fix_source(&src, file, config, opts, rules, options, census)
} else {
let (violations, lex_error) =
run_rules(&src, Some(file.to_path_buf()), config, rules, census);
run_rules(&src, Some(file.to_path_buf()), config, rules, options, census);
(violations, None, 0, lex_error)
}
});
@@ -299,6 +333,7 @@ fn run_rules(
path: Option<PathBuf>,
config: &Config,
rules: &[&'static dyn Rule],
options: &RuleOptions,
census: Option<&Census>,
) -> (Vec<Violation>, Option<String>) {
// One parse per file (TODO §4): the products are built here, once, and
@@ -313,8 +348,13 @@ fn run_rules(
// census so a signal never counts as mentioned by its own declaration.
let elsewhere = census.map(|census| Elsewhere { census, own: words::harvest(parsed.tokens()) });
// The indent width the formatter would use is also the width a tab
// expands to, so `--indent 4` fixes tabs into four spaces.
let ctx = parsed.context(path).with_tab_width(config.indent_width);
// expands to, so `--indent 4` fixes tabs into four spaces — and the width
// it would wrap to is the width `line-length` holds the file to.
let ctx = parsed
.context(path)
.with_tab_width(config.indent_width)
.with_line_length(config.max_width)
.with_options(options);
let ctx = match &elsewhere {
Some(elsewhere) => ctx.with_oracle(elsewhere),
None => ctx,
@@ -361,12 +401,13 @@ fn fix_source(
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
options: &RuleOptions,
census: Option<&Census>,
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
let mut text = src.to_string();
let mut fixed = 0;
let (mut violations, mut lex_error) =
run_rules(&text, Some(file.to_path_buf()), config, rules, census);
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
for _ in 0..MAX_FIX_ROUNDS {
let round =
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
@@ -375,7 +416,8 @@ fn fix_source(
}
fixed += round.applied;
text = round.output;
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules, census);
(violations, lex_error) =
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
}
let rewritten = (text != src).then_some(text);
(violations, rewritten, fixed, lex_error)
+15 -5
View File
@@ -98,7 +98,7 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
if opts.is_stdin() {
let config = match stdin_config(opts) {
let (config, file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -120,7 +120,14 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules);
let options = match lint::rule_options(&file_config) {
Ok(options) => options,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules, &options);
}
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
Ok(jobs) => jobs,
@@ -140,7 +147,7 @@ fn run_check(opts: &Options) -> ExitCode {
fn run_stdin(opts: &Options) -> ExitCode {
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
let config = match stdin_config(opts) {
let (config, _file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -421,13 +428,16 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
/// The settings for a buffer piped in on stdin: discovery anchors on
/// `--stdin-filename`'s directory when given, else on the current one.
fn stdin_config(opts: &Options) -> Result<Config, String> {
/// The formatter config a stdin buffer is served with, and the `lucisv.toml`
/// it came from — the linter needs the file's own `[lint.<rule>]` entries,
/// which the resolved `Config` does not carry.
fn stdin_config(opts: &Options) -> Result<(Config, FileConfig), String> {
let mut discovery = Discovery::new(!opts.no_config);
let file = match opts.stdin_filename.as_deref() {
Some(name) => discovery.for_file(Path::new(name))?,
None => discovery.for_dir(Path::new("."))?,
};
Ok(opts.config_with(&file))
Ok((opts.config_with(&file), file))
}
fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, errors: usize) {
+72 -7
View File
@@ -1863,16 +1863,81 @@ fn an_unknown_rule_in_the_lint_table_is_an_error() {
assert_eq!(code(&out), 2);
}
/// Per-rule tables are named rather than silently ignored, so a user who
/// writes one finds out it does nothing yet.
/// A `[lint.<rule>]` table configures that rule, and the verdict changes
/// with it — §34.0's headline claim, end to end through the real binary.
#[test]
fn a_per_rule_lint_table_is_refused_by_name() {
fn a_per_rule_lint_table_changes_the_verdict() {
let dir = TempDir::new("lint-per-rule");
dir.write("dut.sv", DUT);
dir.write("lucisv.toml", "[lint.unused-signal]\nignore = \"tmp_*\"\n");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(110));
dir.write("m.sv", &wide);
let out = run(&["check", &dir.root()]);
assert!(stderr(&out).contains("per-rule lint settings"), "{}", stderr(&out));
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("line-length"), "over the default 100: {}", stdout(&out));
dir.write("lucisv.toml", "[lint.line-length]\nlength = 130\n");
let out = run(&["check", &dir.root()]);
assert_eq!(stdout(&out), "", "the option raised the limit");
assert_eq!(code(&out), 0);
}
/// A bad entry fails the run naming the config file and the line, which is
/// what tells a user *where* to fix it.
#[test]
fn a_bad_rule_option_fails_the_run_naming_file_and_line() {
let dir = TempDir::new("lint-bad-option");
dir.write("m.sv", "module m;\nendmodule\n");
for (config, wanted) in [
("[lint.line-length]\nlength = 10\n", "must be between"),
("[lint.line-length]\nlen = 120\n", "has no option `len`"),
("[lint.no-such-rule]\nx = 1\n", "unknown rule `no-such-rule`"),
("[lint.no-tabs]\nwidth = 4\n", "takes no options"),
("[lint.signal-name-style]\nstyle_regex = \"[a-\"\n", "not a valid pattern"),
// An escape from another dialect must be refused rather than read
// as a literal, which would silently judge the wrong names (QA,
// 2026-09-04).
("[lint.signal-name-style]\nstyle_regex = \"\\bword\\b\"\n", "unsupported escape `\\b`"),
("[lint.macro-name-style]\nstyle_regex = \"(A)\\1\"\n", "unsupported escape `\\1`"),
] {
dir.write("lucisv.toml", config);
let out = run(&["check", &dir.root()]);
let text = stderr(&out);
assert!(text.contains(wanted), "{config:?}: {text}");
assert!(text.contains("lucisv.toml:2:"), "file and line: {text}");
assert_eq!(code(&out), 2, "{config:?}");
}
// Every one of them names the rule as well as the option, so an error
// read out of a CI log stands on its own.
dir.write("lucisv.toml", "[lint.line-length]\nlength = 10\n");
let text = stderr(&run(&["check", &dir.root()]));
assert!(text.contains("rule `line-length`"), "{text}");
assert!(text.contains("`length` must be between"), "{text}");
}
/// The width `line-length` holds a file to is the width the formatter is
/// configured with, so the two halves of lucisv cannot disagree.
#[test]
fn line_length_follows_the_formatters_width() {
let dir = TempDir::new("lint-width");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(90));
dir.write("m.sv", &wide);
assert_eq!(stdout(&run(&["check", &dir.root()])), "", "under the default 100");
let narrow = run(&["check", &dir.root(), "--line-length", "80"]);
assert!(stdout(&narrow).contains("line-length"), "{}", stdout(&narrow));
dir.write("lucisv.toml", "line-length = 80\n");
let from_config = run(&["check", &dir.root()]);
assert!(stdout(&from_config).contains("line-length"), "{}", stdout(&from_config));
}
/// A stdin buffer reads the same `[lint.<rule>]` tables a file does.
#[test]
fn a_stdin_buffer_reads_the_rule_options_too() {
let dir = TempDir::new("lint-stdin-options");
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
let name = format!("{}/m.sv", dir.root());
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
}
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
+169 -22
View File
@@ -1,8 +1,9 @@
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
//!
//! Only what a small config file needs is supported (comments, `key = int`,
//! `key = "string"`, `key = ["a", "b"]`, and the single table `[lint]`);
//! everything else is rejected by name rather than ignored. See
//! `key = "string"`, `key = ["a", "b"]`, the table `[lint]` and the per-rule
//! `[lint.<rule>]` tables); everything else is rejected by name rather than
//! ignored. See
//! `docs/features/config-discovery/README.md` for the grammar and the
//! reasoning behind not taking a TOML dependency.
@@ -36,6 +37,34 @@ pub struct FileConfig {
pub lint_select: Option<Vec<String>>,
/// `[lint] ignore`: rules dropped from whatever `select` left.
pub lint_ignore: Option<Vec<String>>,
/// `[lint.<rule>]` tables, **as written**: one entry per key, in file
/// order.
///
/// Neither the rule names nor the option names or their values are
/// checked here — this crate does not know the rule registry, exactly as
/// it does not know which rule names `select` may hold. `lucisv check`
/// resolves them against `vlog_linter`'s specs and fails the run naming
/// this file and the line, which is what [`LintOption::line`] is for.
pub lint_options: Vec<LintOption>,
/// The config file these settings were read from, when they were read
/// from one. `parse` leaves it unset — it is handed text, not a path —
/// and [`Discovery`] fills it in, so an error about an entry can name the
/// file the user has to edit.
pub source: Option<PathBuf>,
}
/// One `key = value` written under a `[lint.<rule>]` table, as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintOption {
/// The rule named by the table header.
pub rule: String,
/// The option key.
pub key: String,
/// The value's text, comment stripped, quotes and all — the linter's own
/// parser reads it, because only it knows what kind the key takes.
pub raw: String,
/// 1-based line the entry was written on.
pub line: usize,
}
/// Parses the supported TOML subset. Errors are prefixed `<line>: ` so the
@@ -45,36 +74,55 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
// Editors on some platforms prepend a BOM; it would otherwise garble
// key matching on line 1 into an `unknown key` with invisible cause.
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
// Which table the keys below belong to. There is exactly one table, so
// this is a flag rather than a path: `[lint]` opens it and nothing closes
// it, which is TOML's own rule.
let mut in_lint = false;
// Which table the keys below belong to: the top level until a header
// opens one, and then that one until the next header. Nothing closes a
// table, which is TOML's own rule.
let mut table = Table::Top;
for (index, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
parse_entry(line, &mut config, &mut in_lint).map_err(|e| format!("{}: {e}", index + 1))?;
parse_entry(line, &mut config, &mut table, index + 1)
.map_err(|e| format!("{}: {e}", index + 1))?;
}
Ok(config)
}
fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Result<(), String> {
/// The table whose keys are being read.
enum Table {
/// Before any header: the formatter's own keys.
Top,
/// `[lint]`: `select` and `ignore`.
Lint,
/// `[lint.<rule>]`: that rule's options.
Rule(String),
}
fn parse_entry(
line: &str,
config: &mut FileConfig,
table: &mut Table,
number: usize,
) -> Result<(), String> {
if line.starts_with('[') {
// `[lint]` is the one table lucisv reads. `[lint.<rule>]` — per-rule
// settings — is named in the error rather than ignored, so a user who
// writes one finds out it is not supported yet instead of wondering
// why it did nothing (topo §2.9-4 keeps the per-rule half open).
// `[lint]` carries `select`/`ignore`; `[lint.<rule>]` carries that
// rule's options, which are stored raw and checked by whoever knows
// the registry.
if line == "[lint]" {
*in_lint = true;
*table = Table::Lint;
return Ok(());
}
if line.starts_with("[lint.") {
return Err(format!(
"per-rule lint settings (`{line}`) are not supported yet; `[lint]` takes `select` and `ignore`"
));
if let Some(rule) = line.strip_prefix("[lint.").and_then(|r| r.strip_suffix(']')) {
if rule.is_empty() || rule.contains('.') || rule.contains(' ') {
return Err(format!("`{line}` is not a rule table; write `[lint.<rule-name>]`"));
}
*table = Table::Rule(rule.to_string());
return Ok(());
}
return Err(format!("unknown table `{line}` (the only table is `[lint]`)"));
return Err(format!(
"unknown table `{line}` (the tables are `[lint]` and `[lint.<rule-name>]`)"
));
}
let (key, value) =
line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?;
@@ -83,8 +131,10 @@ fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Resul
if value.is_empty() {
return Err(format!("`{key}` has no value"));
}
if *in_lint {
return parse_lint_entry(key, value, config);
match table {
Table::Lint => return parse_lint_entry(key, value, config),
Table::Rule(rule) => return parse_rule_entry(rule, key, value, config, number),
Table::Top => {}
}
match key {
"line-length" => set_int(&mut config.line_length, key, value, 40, 400),
@@ -105,7 +155,8 @@ fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Resul
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
and select, ignore under `[lint]`)"
select, ignore under `[lint]`; and a rule's own options under \
`[lint.<rule-name>]`)"
)),
}
}
@@ -126,6 +177,26 @@ fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(
Ok(())
}
/// One `key = value` of a `[lint.<rule>]` table, kept as written.
fn parse_rule_entry(
rule: &str,
key: &str,
value: &str,
config: &mut FileConfig,
line: usize,
) -> Result<(), String> {
if config.lint_options.iter().any(|held| held.rule == rule && held.key == key) {
return Err(format!("duplicate key `{key}` under `[lint.{rule}]`"));
}
config.lint_options.push(LintOption {
rule: rule.to_string(),
key: key.to_string(),
raw: value.to_string(),
line,
});
Ok(())
}
fn set_int(
slot: &mut Option<usize>,
key: &str,
@@ -292,6 +363,8 @@ fn load(path: &Path) -> Result<FileConfig, String> {
let dir = path.parent().unwrap_or(Path::new("."));
config.filelist = Some(dir.join(filelist));
}
// So an error about a `[lint.<rule>]` entry can name the file to edit.
config.source = Some(path.to_path_buf());
Ok(config)
}
@@ -451,7 +524,8 @@ exclude = [ \"build\", \"*_gen.sv\", ]
fn the_lint_table_rejects_what_it_does_not_support() {
assert!(err("[lint]\nbogus = [\"a\"]").contains("unknown key `bogus` under `[lint]`"));
assert!(err("[lint]\nselect = \"no-tabs\"").contains("multi-line arrays are unsupported"));
assert!(err("[lint.no-tabs]\nseverity = \"error\"").contains("per-rule lint settings"));
assert!(err("[lint.]\nx = 1").contains("not a rule table"));
assert!(err("[lint.a.b]\nx = 1").contains("not a rule table"));
assert!(err("[lint]\nindent = 4").contains("unknown key `indent` under `[lint]`"));
// A key before any table still belongs to the top level.
assert!(err("select = [\"no-tabs\"]").contains("unknown key `select`"));
@@ -462,6 +536,79 @@ exclude = [ \"build\", \"*_gen.sv\", ]
);
}
/// The per-rule tables: stored exactly as written, because this crate
/// has no idea what a rule is or what its options take.
#[test]
fn a_rule_table_keeps_its_entries_as_written() {
let config = parse(
"[lint]\nignore = [\"no-tabs\"]\n\n\
[lint.line-length]\nlength = 120\n\n\
[lint.signal-name-style]\nstyle_regex = \"[a-z_0-9]+\" # ours\n",
)
.expect("parses");
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
let entries: Vec<(&str, &str, &str, usize)> = config
.lint_options
.iter()
.map(|o| (o.rule.as_str(), o.key.as_str(), o.raw.as_str(), o.line))
.collect();
assert_eq!(
entries,
vec![
("line-length", "length", "120", 5),
("signal-name-style", "style_regex", "\"[a-z_0-9]+\"", 8),
]
);
}
/// A backslash is legal in an option value and refused in a top-level
/// string: the linter's own parser reads the former, and a pattern is the
/// one value that needs them.
#[test]
fn a_rule_option_value_is_not_string_checked_here() {
let config =
parse("[lint.signal-name-style]\nstyle_regex = \"[a-z]\\d+\"\n").expect("parses");
assert_eq!(config.lint_options[0].raw, "\"[a-z]\\d+\"");
assert!(err("exclude = [\"a\\d\"]").contains("escapes"), "still refused up here");
}
#[test]
fn a_rule_table_rejects_a_repeated_key_and_a_bad_header() {
assert!(err("[lint.line-length]\nlength = 1\nlength = 2")
.contains("duplicate key `length` under `[lint.line-length]`"));
// The same key under two different rules is two different options.
let config = parse(
"[lint.enum-name-style]\nstyle_regex = \"a\"\n\
[lint.module-name-style]\nstyle_regex = \"b\"\n",
)
.expect("parses");
assert_eq!(config.lint_options.len(), 2);
assert!(err("[lint.a b]\nx = 1").contains("not a rule table"));
}
/// Nothing closes a table: the keys after a rule header belong to it
/// until the next header, and a formatter key written there is that
/// rule's option as far as this parser is concerned.
#[test]
fn a_rule_table_runs_until_the_next_header() {
let config =
parse("indent = 4\n[lint.line-length]\nlength = 120\nindent = 8\n").expect("parses");
assert_eq!(config.indent, Some(4));
assert_eq!(config.lint_options.len(), 2);
assert_eq!(config.lint_options[1].key, "indent");
}
#[test]
fn a_config_file_records_where_it_came_from() {
let tree = TempTree::new();
let written = tree.write("lucisv.toml", "[lint.line-length]\nlength = 120\n");
let file = tree.write("x.sv", "");
let found = Discovery::new(true).for_file(&file).expect("reads");
assert_eq!(found.source.as_deref(), Some(written.as_path()));
// `parse` alone has no path to record.
assert_eq!(parse("indent = 4").expect("parses").source, None);
}
/// A throwaway directory tree under the system temp dir.
struct TempTree {
path: PathBuf,
+61 -4
View File
@@ -17,7 +17,7 @@ use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use vlog_formatter::fence::{self, Region};
use vlog_linter::{
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
Severity, Violation,
RuleOptions, Severity, Violation,
};
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
@@ -35,14 +35,29 @@ use crate::state::{Document, Workspace};
pub struct LintRun<'a> {
rules: Vec<&'static dyn Rule>,
oracle: Option<IndexMentions<'a>>,
/// What the buffer's `lucisv.toml` and the editor's settings configured
/// about each rule, merged. Empty means every rule reads its own default.
options: RuleOptions,
/// The width `line-length` holds this buffer to — the width the formatter
/// would wrap it to, so the two halves of lucisv cannot disagree.
line_length: usize,
}
impl Default for LintRun<'_> {
fn default() -> LintRun<'static> {
LintRun { rules: default_rules(), oracle: None }
LintRun {
rules: default_rules(),
oracle: None,
options: RuleOptions::new(),
line_length: DEFAULT_LINE_LENGTH,
}
}
}
/// The width a buffer is held to when neither its `lucisv.toml` nor the
/// editor says otherwise — `vlog_formatter::Config`'s own default.
const DEFAULT_LINE_LENGTH: usize = 100;
impl<'a> LintRun<'a> {
/// The pass this workspace's settings and index describe for one buffer.
///
@@ -58,12 +73,13 @@ impl<'a> LintRun<'a> {
let workspace = index.files().len() > usize::from(own.is_some());
let rules = enabled_rules(ws.client_settings(), workspace);
let oracle = workspace.then_some(IndexMentions { index, own });
LintRun { rules, oracle }
let (options, line_length) = configured(ws.client_settings(), doc);
LintRun { rules, oracle, options, line_length }
}
/// This run's context over a buffer's own parse products.
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
let ctx = context(doc);
let ctx = context(doc).with_options(&self.options).with_line_length(self.line_length);
match &self.oracle {
Some(oracle) => ctx.with_oracle(oracle),
None => ctx,
@@ -71,6 +87,47 @@ impl<'a> LintRun<'a> {
}
}
/// The per-rule options and the line width governing one buffer.
///
/// **Precedence for an option, highest first: the editor, then the buffer's
/// `lucisv.toml`, then the rule's own default — key by key**, so a project
/// that sets two options and a user who overrides one keep the other. This is
/// deliberately the *opposite* order to `format::settings_for`, where a
/// checked-in `lucisv.toml` outranks the editor: formatting has a byte-exact
/// contract with CI that a user's editor must not break, while a lint option
/// changes which findings that user is shown in their own editor and is
/// theirs to set. §34.0(d).
///
/// The **width** follows the formatting ladder instead, because it is not a
/// lint setting at all: it is the width the formatter would wrap this buffer
/// to, read the same way `format::settings_for` reads it, so a line lucisv
/// wrote is never a line lucisv calls too long. `line-length`'s own `length`
/// option still beats it — that is the rule's own business, and the rule
/// applies it.
///
/// The config file is read here, per pass, exactly as `format::discover`
/// reads it per formatting request: a `lucisv.toml` edited while the server
/// runs takes effect at the next publish, and the read is a few stats beside
/// a parse and an analysis the same pass already paid for.
fn configured(client: &ClientSettings, doc: &Document) -> (RuleOptions, usize) {
let file = doc
.path
.as_deref()
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
.unwrap_or_default();
let mut options = RuleOptions::new();
for entry in &file.lint_options {
// A broken entry in the file is dropped here rather than reported:
// `format::settings_for` already surfaces a `lucisv.toml` problem to
// the user, and `lucisv check` fails the run over it with file and
// line, which is where a config error belongs.
let _ = options.set_raw(&entry.rule, &entry.key, &entry.raw);
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
(options, width)
}
/// 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:
@@ -12,12 +12,13 @@ use lsp_server::{ExtractError, Notification};
use lsp_types::notification::{
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
DidRenameFiles, DidSaveTextDocument, Notification as _,
DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _,
};
use lsp_types::{
DeleteFilesParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
DidChangeWatchedFilesParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, RenameFilesParams, Uri, WorkspaceFolder,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, LogMessageParams, MessageType,
RenameFilesParams, Uri, WorkspaceFolder,
};
use serde::de::DeserializeOwned;
@@ -244,14 +245,30 @@ impl Server {
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
let watched = self.workspace.filelist_path();
let linted = self.lint_selection();
// A `lucisv.lint.options` entry the registry refused is dropped, not
// fatal (`settings::rule_options`) — so the log line is the only way
// the user learns their option is doing nothing. Logged, not shown: a
// typo in a settings file is not worth a popup, and a client that
// resends its whole section would raise the same one repeatedly.
for warning in &settings.lint_option_warnings {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {warning}"),
},
);
}
// Only `exclude` and `filelist` change which files exist as far as
// this server is concerned; the other settings are read afresh by the
// next request that wants them and need no invalidation.
if self.workspace.set_client_settings(settings) {
self.reindex();
} else if self.lint_selection() != linted {
// `lucisv.lint.select`/`ignore` change which rules run and nothing
// else: no file's contents moved, so there is nothing to rescan —
// `lucisv.lint.select`/`ignore`, the class switches, the per-rule
// toggles and the per-rule *options* change which rules run and
// what they report, and nothing else: no file's contents moved,
// so there is nothing to rescan —
// but every published squiggle was drawn under the old selection,
// and a client that pulls has cached answers under it too.
self.generation += 1;
+151 -4
View File
@@ -17,7 +17,7 @@ use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use serde_json::Value;
use vlog_linter::Severity;
use vlog_linter::{OptionValue, RuleOptions, Severity};
/// Accepted `line-length`, and accepted `indent`.
///
@@ -190,6 +190,18 @@ pub struct ClientSettings {
/// toggle nobody touched would silently override `select` and the class
/// switches.
pub lint_rules: BTreeMap<String, bool>,
/// `lucisv.lint.options`: `{"<rule>": {"<key>": value}}`, validated
/// against the rule registry.
///
/// Refused entries are **dropped**, not fatal — this module's standing
/// rule, and the reason it matters here more than anywhere else: one
/// typo in an options object must not be able to switch the linter off
/// for a whole session. What was refused is kept in
/// [`ClientSettings::lint_option_warnings`] so the user is told.
pub lint_options: RuleOptions,
/// One line per refused `lucisv.lint.options` entry, ready for a
/// `window/logMessage`. Empty for a settings push that was all valid.
pub lint_option_warnings: Vec<String>,
}
/// The settings a client that said nothing is treated as having asked for.
@@ -218,6 +230,8 @@ impl Default for ClientSettings {
lint_ignore: Vec::new(),
lint_severity: every_class_on(),
lint_rules: BTreeMap::new(),
lint_options: RuleOptions::new(),
lint_option_warnings: Vec::new(),
}
}
}
@@ -233,15 +247,21 @@ fn every_class_on() -> BTreeMap<Severity, bool> {
/// 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<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>);
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>, RuleOptions);
/// The four lint settings of `settings`, as one comparable value.
/// The lint settings of `settings`, as one comparable value.
///
/// The options are in here with the four that choose rules, because a changed
/// option changes what a rule *reports* — a `line-length` of 120 unpublishes
/// every finding drawn at 100 — and every open file must be published again
/// for exactly the same reason a changed selection does.
pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
(
settings.lint_select.clone(),
settings.lint_ignore.clone(),
settings.lint_severity.clone(),
settings.lint_rules.clone(),
settings.lint_options.clone(),
)
}
@@ -272,6 +292,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
let large_file = lucisv.get("largeFile");
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
let lint = lucisv.get("lint");
let (options, warnings) = rule_options(lint.and_then(|l| l.get("options")));
ClientSettings {
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
@@ -319,6 +340,8 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// 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"))),
lint_options: options,
lint_option_warnings: warnings,
}
}
@@ -364,6 +387,63 @@ fn rule_toggles(value: Option<&Value>) -> BTreeMap<String, bool> {
.collect()
}
/// The `lucisv.lint.options` object, validated against the rule registry.
///
/// The shape is `{"<rule>": {"<key>": value}}` — the nesting VS Code's
/// settings model produces for an object setting, and the one a hand-written
/// Neovim config writes. Every entry goes through the **same** validator a
/// `[lint.<rule>]` table in a `lucisv.toml` goes through
/// (`RuleOptions::set`), so an option means one thing in both front ends.
///
/// A refused entry is dropped and described, rather than failing the push:
/// the CLI can fail a run over a typo because a user typed it and is watching,
/// while a settings push arrives on a socket and failing it would leave an
/// editor with no diagnostics and no way to see why. The descriptions are
/// returned for the caller to log.
fn rule_options(value: Option<&Value>) -> (RuleOptions, Vec<String>) {
let mut options = RuleOptions::new();
let mut warnings = Vec::new();
let Some(Value::Object(rules)) = value else { return (options, warnings) };
for (rule, keys) in rules {
let Some(Value::Object(keys)) = Some(keys) else {
warnings.push(format!("lucisv.lint.options.{rule} is not an object; ignored"));
continue;
};
for (key, raw) in keys {
let Some(value) = option_value(raw) else {
warnings.push(format!(
"lucisv.lint.options.{rule}.{key}: {raw} is not a boolean, number, \
string or list of strings; ignored"
));
continue;
};
if let Err(problem) = options.set(rule, key, value) {
warnings.push(format!("lucisv.lint.options.{rule}.{key}: {problem}; ignored"));
}
}
}
(options, warnings)
}
/// One JSON value as an option value, or nothing for a shape no option takes.
///
/// Structural only — whether the *kind* is the one the option declares is
/// `RuleOptions::set`'s answer, so the error a user reads names the option
/// and its kind rather than JSON's.
fn option_value(raw: &Value) -> Option<OptionValue> {
match raw {
Value::Bool(b) => Some(OptionValue::Bool(*b)),
Value::Number(n) => n.as_i64().map(OptionValue::Int),
Value::String(s) => Some(OptionValue::Str(s.clone())),
Value::Array(items) => items
.iter()
.map(|item| item.as_str().map(str::to_string))
.collect::<Option<Vec<String>>>()
.map(OptionValue::List),
_ => None,
}
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
/// case and all — because the enum in `package.json` is what a settings UI
/// offers, and forgiving `"Workspace"` here would make a typo mean something
@@ -813,7 +893,9 @@ mod tests {
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] {
let mut configured = base.clone();
configured.lint_options.set_raw("line-length", "length", "120").expect("accepted");
for changed in [severity, toggled, selected, ignored, configured] {
assert_ne!(lint_selection(&base), lint_selection(&changed));
}
// A setting that does not change which rules run does not republish.
@@ -822,6 +904,71 @@ mod tests {
assert_eq!(lint_selection(&base), lint_selection(&unrelated));
}
/// §34.0(c): the object is read, validated against the registry, and a
/// bad entry is dropped **with a warning** rather than failing the push.
#[test]
fn the_lint_options_object_is_read_and_validated() {
let found = settings(json!({"lucisv": {"lint": {"options": {
"line-length": {"length": 120},
"generate-label-prefix": {"prefix": ["blk_"]},
"typedef-structs-unions": {"allow_anonymous_nested": true},
"signal-name-style": {"style_regex": "[a-z_0-9]+"},
}}}}));
assert_eq!(found.lint_options.int("line-length", "length"), 120);
assert_eq!(
found.lint_options.list("generate-label-prefix", "prefix"),
vec!["blk_".to_string()]
);
assert!(found.lint_options.bool("typedef-structs-unions", "allow_anonymous_nested"));
assert_eq!(found.lint_options.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
assert!(found.lint_option_warnings.is_empty(), "{:?}", found.lint_option_warnings);
}
#[test]
fn a_refused_option_is_dropped_and_described_rather_than_fatal() {
let found = settings(json!({"lucisv": {"lint": {"options": {
"line-length": {"length": 10, "len": 120},
"no-such-rule": {"x": 1},
"no-tabs": {"width": 4},
"signal-name-style": {"style_regex": "[a-"},
"interface-name-style": {"style_regex": "\\bword\\b"},
"macro-name-style": {"style_regex": 4},
"package-filename": "not-an-object",
"port-name-suffix": {"suffixes": [1, 2]},
}}}}));
// Nothing was accepted, and every refusal says which entry and why.
assert!(found.lint_options.is_empty(), "{:?}", found.lint_options);
let warnings = found.lint_option_warnings.join("\n");
for wanted in [
"line-length.length",
"must be between",
"has no option `len`",
"unknown rule `no-such-rule`",
"takes no options",
"not a valid pattern",
"unsupported escape `\\b`",
"expects a pattern, found an integer",
"package-filename is not an object",
"port-name-suffix.suffixes",
] {
assert!(warnings.contains(wanted), "{wanted} missing from:\n{warnings}");
}
// ... and the rest of the settings survived the bad object.
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE);
}
/// A settings payload with no options object is exactly today's
/// behaviour: every rule reads its own default.
#[test]
fn no_options_object_means_every_default() {
for payload in [json!({"lucisv": {}}), json!({"lucisv": {"lint": {}}})] {
let found = settings(payload);
assert!(found.lint_options.is_empty());
assert!(found.lint_option_warnings.is_empty());
assert_eq!(found.lint_options.int("line-length", "length"), 100, "the spec default");
}
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
+76
View File
@@ -9,12 +9,20 @@ use vlog_parser::token::{Comment, Token, TokenKind};
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LexError, LineIndex};
use vlog_semantic::{analyze, Semantics};
use crate::options::RuleOptions;
use crate::signals::Signals;
/// The default tab stop used when a fix expands a tab, matching lucisv's
/// default indent. `LintContext::with_tab_width` follows `--indent`.
const DEFAULT_TAB_WIDTH: usize = 2;
/// The width `line-length` holds a file to when nothing says otherwise —
/// `vlog_formatter::Config`'s own default, because the two are the same
/// number: a formatted file that the linter then calls too wide would be
/// lucisv disagreeing with itself. `LintContext::with_line_length` follows
/// `--line-length` and `lucisv.toml`.
const DEFAULT_LINE_LENGTH: usize = 100;
/// One text, parsed once: the products a lint run reads.
///
/// This is the owned half of "one parse, two tools" (TODO §4): a caller with
@@ -201,6 +209,10 @@ pub struct LintContext<'a> {
backing: Backing<'a>,
path: Option<PathBuf>,
tab_width: usize,
line_length: usize,
/// What the run configured about each rule, or `None` for a run that
/// configured nothing — which reads exactly as the specs' own defaults.
options: Option<&'a RuleOptions>,
/// Byte ranges of string literals, ascending — the one place text rules
/// must not rewrite, because there whitespace is data.
strings: Vec<TextRange>,
@@ -254,6 +266,8 @@ impl<'a> LintContext<'a> {
backing,
path,
tab_width: DEFAULT_TAB_WIDTH,
line_length: DEFAULT_LINE_LENGTH,
options: None,
strings: Vec::new(),
semantics: SemanticsSlot::Lazy(OnceCell::new()),
signals: OnceCell::new(),
@@ -271,6 +285,68 @@ impl<'a> LintContext<'a> {
self
}
/// Sets the width the run's formatter would wrap to, which is what
/// `line-length` holds the file to unless that rule's own `length` option
/// says otherwise.
pub fn with_line_length(mut self, line_length: usize) -> LintContext<'a> {
self.line_length = line_length.max(1);
self
}
/// Lends the per-rule options the run resolved. A context without them
/// reads every option at its declared default, which is the shipped
/// behaviour.
pub fn with_options(mut self, options: &'a RuleOptions) -> LintContext<'a> {
self.options = Some(options);
self
}
/// The width the run's formatter wraps to. See
/// [`with_line_length`](LintContext::with_line_length).
pub fn line_length(&self) -> usize {
self.line_length
}
/// What the run configured, or the empty set.
pub fn options(&self) -> &RuleOptions {
match self.options {
Some(options) => options,
None => RuleOptions::none(),
}
}
/// One boolean option of `rule`, or its declared default.
pub fn option_bool(&self, rule: &str, key: &str) -> bool {
self.options().bool(rule, key)
}
/// One integer option of `rule`, or its declared default.
pub fn option_int(&self, rule: &str, key: &str) -> i64 {
self.options().int(rule, key)
}
/// One string (or pattern) option of `rule`, or its declared default.
pub fn option_str(&self, rule: &str, key: &str) -> &str {
self.options().str(rule, key)
}
/// One list option of `rule`, or its declared default.
pub fn option_list(&self, rule: &str, key: &str) -> Vec<String> {
self.options().list(rule, key)
}
/// Whether the run said anything about this option at all — the question
/// a rule asks when its fallback is not its spec's default.
pub fn option_is_set(&self, rule: &str, key: &str) -> bool {
self.options().is_set(rule, key)
}
/// One pattern option of `rule`, compiled, or `None` if it does not
/// compile — which cannot happen for a value this run accepted.
pub(crate) fn option_pattern(&self, rule: &str, key: &str) -> Option<crate::regex::Regex> {
crate::options::pattern(self.options(), rule, key)
}
/// Lends the symbol table the caller already built for this exact text —
/// "one parse, two tools" extended to the analysis (the language server
/// analyzes every buffer anyway, so its lint pass must not analyze twice).
+102
View File
@@ -12,6 +12,7 @@ use vlog_parser::ast::{
DataType, Dim, EnumType, FunctionDecl, ItemKind, ListElem, SourceFile, StmtKind, StructType,
TaskDecl, TfArg, TypeExtra, TypedefKind,
};
use vlog_parser::span::TextRange;
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
@@ -147,6 +148,107 @@ fn struct_types(struct_ty: &StructType, visit: &mut dyn FnMut(&DataType)) {
}
}
/// A type written in a declaration, with the name that declaration gives.
///
/// What the two `typedef-*` rules need and `walk_data_types` cannot say: a
/// `DataType` carries no span of its own, so a rule that judges the *type* of
/// a declaration reports at the name — and needs to know whether that
/// declaration is nested inside another aggregate's body.
pub(crate) struct DeclaredType<'a> {
/// The type as written.
pub(crate) ty: &'a DataType,
/// The name declared with it.
pub(crate) name: &'a str,
/// Byte range of that name — where a finding points.
pub(crate) span: TextRange,
/// True when this declaration is a member of another `struct`/`union`.
pub(crate) nested: bool,
}
/// Calls `f` on every type written in a **declaration** — a data or port
/// declaration, an ANSI port, a variable declaration in a statement — and on
/// every member of an aggregate written inside one.
///
/// A `typedef`'s own base type is deliberately not visited: a named type is
/// exactly what the `typedef-*` rules ask for, so passing it to them would be
/// asking them to flag the shape they exist to encourage. Its members are
/// visited, as nested declarations.
pub(crate) fn walk_declared_types(file: &SourceFile, f: &mut dyn FnMut(&DeclaredType)) {
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 {
declared(&port.ty, &port.name, port.name_span, false, f);
}
}
}
ItemKind::DataDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
ItemKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
// Only the members: the typedef itself is the named type these rules
// want, and the naming rules judge its name.
ItemKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
StmtKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
StmtKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
_ => {}
});
}
/// One declaration, and whatever aggregate its type carries.
fn declared(
ty: &DataType,
name: &str,
span: TextRange,
nested: bool,
f: &mut dyn FnMut(&DeclaredType),
) {
f(&DeclaredType { ty, name, span, nested });
members_of(ty, f);
}
/// One declaration's type, once per name it declares.
fn declarator_types(
ty: &DataType,
declarators: &[vlog_parser::ast::Declarator],
f: &mut dyn FnMut(&DeclaredType),
) {
for declarator in declarators {
declared(ty, &declarator.name, declarator.name_span, false, f);
}
}
/// The members of an anonymous aggregate, and of the aggregates inside it.
fn members_of(ty: &DataType, f: &mut dyn FnMut(&DeclaredType)) {
if let Some(TypeExtra::Struct(structure)) = ty.inline() {
struct_members(structure, f);
}
}
/// The members of a `struct`/`union` body, each as a nested declaration.
fn struct_members(structure: &StructType, f: &mut dyn FnMut(&DeclaredType)) {
for member in &structure.members {
for declarator in &member.declarators {
f(&DeclaredType {
ty: &member.ty,
name: &declarator.name,
span: declarator.name_span,
nested: true,
});
}
members_of(&member.ty, f);
}
}
/// A typedef's members — everything inside its body, but not the body itself.
fn typedef_members(kind: &TypedefKind, f: &mut dyn FnMut(&DeclaredType)) {
if let TypedefKind::Struct(structure) = kind {
struct_members(structure, f);
}
}
/// 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)) {
+7 -2
View File
@@ -24,7 +24,10 @@ mod context;
mod decls;
mod interfaces;
mod literal;
mod module_decls;
mod naming;
mod options;
mod regex;
mod registry;
mod rule_docs;
mod rules;
@@ -39,6 +42,7 @@ use std::path::PathBuf;
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
pub use interfaces::module_interfaces;
pub use options::{OptionDefault, OptionKind, OptionSpec, OptionValue, RuleOptions};
pub use registry::{
all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule,
};
@@ -197,11 +201,12 @@ mod tests {
// Real corpus RTL is annotated for Verible. Waivers naming rules lucisv
// has not implemented are that codebase's, not typos, so they are
// neither honored nor reported.
let src = "module m;\n // verilog_lint: waive macro-name-style\n wire a;\nendmodule\n";
let src = "module m;\n // verilog_lint: waive explicit-function-lifetime\n wire a;\nendmodule\n";
assert!(lint_all(src).is_empty());
// lucisv's own spelling gets no such benefit of the doubt.
let src = "module m;\n // lucisv: waive macro-name-style\n wire a;\nendmodule\n";
let src =
"module m;\n // lucisv: waive explicit-function-lifetime\n wire a;\nendmodule\n";
assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]);
}
+231
View File
@@ -0,0 +1,231 @@
//! The nets, variables and ports a module declares — what the two signal
//! naming rules judge.
//!
//! A module's own declarations are a different population from "every
//! declared name in the file": a class property, a loop variable and a
//! function local are not signals, and a rule that judged them would be
//! reporting on things the style guide says nothing about. Collecting them
//! lives here rather than in `visit` (the item and statement spines) or
//! `decls` (types and dimensions), so each of the three files stays one
//! sentence long.
use vlog_parser::ast::{AnsiPort, GenBlock, GenElse, Item, ItemKind, PortList, SourceFile};
use vlog_parser::span::TextRange;
/// One net, variable or port a module declares.
pub(crate) struct SignalDecl {
/// The declared name, as written.
pub(crate) name: String,
/// Byte range of that name.
pub(crate) span: TextRange,
/// The word a diagnostic calls it: `port` or `signal`.
pub(crate) what: &'static str,
/// The direction of a port, as written (`input`, `output`, `inout`), or
/// `None` for a signal.
pub(crate) dir: Option<String>,
}
/// Every net, variable and port declared inside a module, interface or
/// program of `file`, header and body alike, generate blocks included.
///
/// A `class` body is deliberately not descended into: its properties are not
/// signals. A function or task body is not either — a local is scoped to the
/// subroutine and named for it.
pub(crate) fn module_signals(file: &SourceFile) -> Vec<SignalDecl> {
let mut out = Vec::new();
for item in &file.items {
collect_item(item, &mut out);
}
out
}
fn collect_item(item: &Item, out: &mut Vec<SignalDecl>) {
match &item.kind {
ItemKind::Module(module) => {
header_ports(&module.ports, out);
for inner in &module.items {
collect_body(inner, out);
}
}
// A module may be written inside a package; nothing else at file
// level holds one.
ItemKind::Package { items, .. } => {
for inner in items {
collect_item(inner, out);
}
}
_ => {}
}
}
/// One item of a module body.
fn collect_body(item: &Item, out: &mut Vec<SignalDecl>) {
match &item.kind {
ItemKind::DataDecl(decl) => {
for declarator in &decl.declarators {
out.push(SignalDecl {
name: declarator.name.clone(),
span: declarator.name_span,
what: "signal",
dir: None,
});
}
}
ItemKind::PortDecl(decl) => {
for declarator in &decl.declarators {
out.push(SignalDecl {
name: declarator.name.clone(),
span: declarator.name_span,
what: "port",
dir: Some(decl.dir.clone()),
});
}
}
// A nested module is a module of its own.
ItemKind::Module(_) => collect_item(item, out),
ItemKind::GenerateRegion { items, .. } => {
for inner in items {
collect_body(inner, out);
}
}
ItemKind::GenIf(gen_if) => {
block(&gen_if.then, out);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
block(&nested.then, out);
els = nested.els.as_deref();
}
GenElse::Block(inner) => {
block(inner, out);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => block(&gen_for.body, out),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
block(&case_item.body, out);
}
}
_ => {}
}
}
fn block(block: &GenBlock, out: &mut Vec<SignalDecl>) {
for item in &block.items {
collect_body(item, out);
}
}
/// The ports of a module header, in either style.
fn header_ports(ports: &PortList, out: &mut Vec<SignalDecl>) {
match ports {
PortList::Ansi(ports) => {
// A port with no direction keyword continues the previous one, as
// the language says; a first port with none is `inout` by default.
let mut carried: Option<String> = None;
for port in ports {
carried = direction(port).or(carried);
out.push(SignalDecl {
name: port.name.clone(),
span: port.name_span,
what: "port",
dir: carried.clone(),
});
}
}
// A non-ANSI header *names* its ports; the body declares them
// (`input clk;`), and that declaration is the one collected — so a
// rule reports each port once, where its direction is written.
PortList::NonAnsi(_) | PortList::None | PortList::Empty => {}
}
}
fn direction(port: &AnsiPort) -> Option<String> {
port.dir.clone()
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn signals(src: &str) -> Vec<(String, &'static str, Option<String>)> {
let (file, _) = parse_source_tolerant(src);
module_signals(&file).into_iter().map(|decl| (decl.name, decl.what, decl.dir)).collect()
}
#[test]
fn collects_header_ports_body_ports_and_signals() {
let src = "module m (input logic clk, output data);\n\
\x20 wire a;\n\
\x20 logic [7:0] b, c;\n\
endmodule\n";
assert_eq!(
signals(src),
vec![
("clk".to_string(), "port", Some("input".to_string())),
("data".to_string(), "port", Some("output".to_string())),
("a".to_string(), "signal", None),
("b".to_string(), "signal", None),
("c".to_string(), "signal", None),
]
);
}
#[test]
fn a_port_with_no_direction_continues_the_previous_one() {
let src = "module m (input logic a, b, output c);\nendmodule\n";
let dirs: Vec<Option<String>> = signals(src).into_iter().map(|s| s.2).collect();
assert_eq!(
dirs,
vec![Some("input".to_string()), Some("input".to_string()), Some("output".to_string())]
);
}
/// A non-ANSI port is declared once, in the body: the header only lists
/// the names, and collecting those too would report every such port
/// twice.
#[test]
fn a_non_ansi_port_is_collected_where_the_body_declares_it() {
let src = "module m (a, b);\n input a;\n output b;\nendmodule\n";
assert_eq!(
signals(src),
vec![
("a".to_string(), "port", Some("input".to_string())),
("b".to_string(), "port", Some("output".to_string())),
]
);
}
#[test]
fn generate_blocks_are_descended_into_and_class_bodies_are_not() {
let src = "module m;\n\
\x20 generate\n\
\x20 if (A) begin : g\n wire in_gen;\n end\n\
\x20 endgenerate\n\
\x20 for (genvar i = 0; i < 2; i++) begin : l\n wire looped;\n end\n\
endmodule\n\
class c;\n logic property_of_a_class;\nendclass\n";
let names: Vec<String> = signals(src).into_iter().map(|s| s.0).collect();
assert_eq!(names, vec!["in_gen".to_string(), "looped".to_string()]);
}
#[test]
fn an_interface_and_a_module_in_a_package_are_covered() {
let src = "interface i (input clk);\n wire w;\nendinterface\n\
package p;\n module inner;\n wire deep;\n endmodule\nendpackage\n";
let names: Vec<String> = signals(src).into_iter().map(|s| s.0).collect();
assert_eq!(names, vec!["clk".to_string(), "w".to_string(), "deep".to_string()]);
}
#[test]
fn a_function_local_is_not_a_signal() {
let src = "module m;\n function void f();\n logic local_var;\n endfunction\n\
endmodule\n";
assert!(signals(src).is_empty());
}
}
+106 -21
View File
@@ -1,13 +1,12 @@
//! The naming-style presets the naming rules check against.
//!
//! Verible spells its naming conventions as RE2 regular expressions. lucisv
//! spells the same conventions as character-class predicates instead, on
//! purpose: every preset anyone actually uses is "these character classes, in
//! this order", which is four small functions — and a regex engine is a
//! dependency this crate (today: `vlog_parser` + std) does not otherwise need.
//! The cost is that user-supplied patterns are not expressible; that waits on
//! the `lint` key in `lucisv.toml` and is recorded as such in
//! `docs/features/lint-rules-2/README.md`.
//! Verible spells its naming conventions as RE2 regular expressions, and
//! since §34 so does lucisv: `crate::regex` reads the subset a style guide is
//! written in, and each naming rule takes the pattern as an option whose
//! default is the preset it shipped with. What survives here are the two
//! `CamelCase`/`ALL_CAPS` predicates — Verible spells those as *words* in
//! `parameter_style`, not as patterns — and the three small helpers every
//! naming rule shares.
//!
//! An **escaped identifier** (`\my$name `) is exempt from every style: its
//! whole point is to carry characters no convention allows.
@@ -17,13 +16,6 @@ pub(crate) fn is_escaped(name: &str) -> bool {
name.starts_with('\\')
}
/// `lower_snake_case`: starts with a lowercase letter, then lowercase
/// letters, digits and underscores.
pub(crate) fn is_lower_snake_case(name: &str) -> bool {
starts_with(name, char::is_ascii_lowercase)
&& name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
/// `UPPER_SNAKE_CASE`: starts with an uppercase letter, then uppercase
/// letters, digits and underscores. Verible calls this preset `ALL_CAPS`.
pub(crate) fn is_upper_snake_case(name: &str) -> bool {
@@ -37,6 +29,80 @@ pub(crate) fn is_camel_case(name: &str) -> bool {
starts_with(name, char::is_ascii_uppercase) && name.chars().all(|c| c.is_ascii_alphanumeric())
}
/// The vocabulary Verible's `*_style` options are written in, and the one
/// [`matches_style_words`] reads.
pub(crate) const STYLE_WORDS: [&str; 2] = ["CamelCase", "ALL_CAPS"];
/// Whether `name` fits any of the `|`-separated preset words of a `*_style`
/// option (`CamelCase|ALL_CAPS`). A word outside the vocabulary cannot reach
/// here — the option refuses it — so an unknown one simply matches nothing.
pub(crate) fn matches_style_words(name: &str, spelling: &str) -> bool {
spelling.split('|').map(str::trim).any(|word| match word {
"CamelCase" => is_camel_case(name),
"ALL_CAPS" => is_upper_snake_case(name),
_ => false,
})
}
/// Whether `name` is one this rule accepts, given a `*_style_regex` override
/// the run may have set and the `*_style` words otherwise.
///
/// The two-key shape is Verible's: the words are what a style guide says, and
/// the pattern is the escape hatch for a project whose convention is neither.
/// An override that does not compile cannot be set (the option is validated
/// when it is read), so a `None` pattern here means "nobody set one".
pub(crate) fn fits_style(
ctx: &crate::context::LintContext,
rule: &str,
style_key: &str,
regex_key: &str,
name: &str,
) -> bool {
if ctx.option_is_set(rule, regex_key) {
return match ctx.option_pattern(rule, regex_key) {
Some(pattern) => pattern.is_match(name),
None => true,
};
}
matches_style_words(name, ctx.option_str(rule, style_key))
}
/// Whether `name` matches this rule's single pattern option — the shape the
/// three type-and-module naming rules take.
pub(crate) fn fits_pattern(
ctx: &crate::context::LintContext,
rule: &str,
regex_key: &str,
name: &str,
) -> bool {
match ctx.option_pattern(rule, regex_key) {
Some(pattern) => pattern.is_match(name),
// Unreachable for a validated option; being quiet is the safe
// direction for a rule that cannot tell what it was asked.
None => true,
}
}
/// What a naming rule says about a name it rejected.
///
/// A run that configured nothing reads the preset's own words — the sentence
/// the rule has always printed, so a default run's diagnostics are the ones
/// CI already has — and a run that set a pattern is told **which** pattern it
/// failed, because "is not lower_snake_case" would be a lie there.
pub(crate) fn style_message(
ctx: &crate::context::LintContext,
rule: &str,
regex_key: &str,
subject: &str,
preset: &str,
) -> String {
if ctx.option_is_set(rule, regex_key) {
format!("{subject} does not match `{}`", ctx.option_str(rule, regex_key))
} else {
format!("{subject} {preset}")
}
}
/// True when `name` is non-empty and its first character passes `first`.
fn starts_with(name: &str, first: impl Fn(&char) -> bool) -> bool {
name.chars().next().is_some_and(|c| first(&c))
@@ -46,13 +112,32 @@ fn starts_with(name: &str, first: impl Fn(&char) -> bool) -> bool {
mod tests {
use super::*;
/// The `lower_snake_case` preset the three type-and-module naming rules
/// used before §34 gave them `style_regex` is now spelled as the pattern
/// `[a-z][a-z_0-9]*`, and the two accept exactly the same names — which
/// is what keeps those rules' findings byte-identical.
#[test]
fn lower_snake_case_accepts_what_rtl_writes() {
for name in ["a", "clk", "data_i", "fifo2_wr_en", "a1_b2"] {
assert!(is_lower_snake_case(name), "{name}");
}
for name in ["", "Clk", "_clk", "clkA", "clk-en", "CLK", "1clk"] {
assert!(!is_lower_snake_case(name), "{name}");
fn the_lower_snake_case_pattern_is_the_preset_it_replaced() {
let pattern = crate::regex::Regex::compile("[a-z][a-z_0-9]*").expect("compiles");
let preset = |name: &str| {
name.chars().next().is_some_and(|c| c.is_ascii_lowercase())
&& name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
};
for name in [
"a",
"clk",
"data_i",
"fifo2_wr_en",
"a1_b2",
"",
"Clk",
"_clk",
"clkA",
"clk-en",
"CLK",
"1clk",
] {
assert_eq!(pattern.is_match(name), preset(name), "{name}");
}
}
+602
View File
@@ -0,0 +1,602 @@
//! Per-rule options: what a rule may be configured with, and the validated
//! map one run carries.
//!
//! Verible gives most of its rules a handful of options (`style_regex`,
//! `length`, the `*_enable` switches) and spells them
//! `--rules=rule-name=option:value`. lucisv spells them where its other
//! settings already live — a `[lint.<rule>]` table in `lucisv.toml`, a
//! `lucisv.lint.options` object in the editor — and both doors come through
//! this module, so the two front ends cannot disagree about what a value
//! means or which values are refused.
//!
//! A rule never sees "unset": every read falls back to the spec's own
//! default, which is also the default the generated rule reference prints.
//! See `docs/features/linter-expansion-2/README.md`.
use std::collections::BTreeMap;
use crate::regex::Regex;
use crate::registry::rule_by_name;
/// What kind of value one option takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionKind {
/// `true` / `false`.
Bool,
/// An integer within the inclusive bounds.
Int {
/// Smallest accepted value.
min: i64,
/// Largest accepted value.
max: i64,
},
/// Any string.
Str,
/// A string that must compile as a pattern (see [`crate::regex`]).
Regex,
/// A list of strings.
List,
/// A list of strings, each of which must compile as a pattern.
RegexList,
/// One or more words from a fixed vocabulary, joined with `|` — how
/// Verible writes `parameter_style:CamelCase|ALL_CAPS`.
Words(&'static [&'static str]),
}
impl OptionKind {
/// The word `--rules-doc` and the settings UI name this kind with.
pub fn as_str(self) -> &'static str {
match self {
OptionKind::Bool => "boolean",
OptionKind::Int { .. } => "integer",
OptionKind::Str => "string",
OptionKind::Regex => "pattern",
OptionKind::List => "list of strings",
OptionKind::RegexList => "list of patterns",
OptionKind::Words(_) => "`|`-separated word list",
}
}
/// The vocabulary a [`OptionKind::Words`] option accepts, for the
/// generated reference; empty for every other kind.
pub fn vocabulary(self) -> &'static [&'static str] {
match self {
OptionKind::Words(words) => words,
_ => &[],
}
}
}
/// One option's value, as a run holds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OptionValue {
/// A boolean.
Bool(bool),
/// An integer.
Int(i64),
/// A string — a pattern included, which is a string that compiled.
Str(String),
/// A list of strings.
List(Vec<String>),
}
impl OptionValue {
/// The word an error message calls this value's kind, so "expects an
/// integer, found a list" reads as a sentence.
fn kind_word(&self) -> &'static str {
match self {
OptionValue::Bool(_) => "a boolean",
OptionValue::Int(_) => "an integer",
OptionValue::Str(_) => "a string",
OptionValue::List(_) => "a list",
}
}
}
/// One option's default, as a rule declares it.
///
/// A second type rather than an [`OptionValue`], because a spec lives in a
/// `static` table: `&'static str` and `&'static [&'static str]` are
/// constructible there and `String`/`Vec<String>` are not. [`Self::value`]
/// is the bridge for a caller that wants the owned form.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionDefault {
/// A boolean default.
Bool(bool),
/// An integer default.
Int(i64),
/// A string (or pattern) default.
Str(&'static str),
/// A list default.
List(&'static [&'static str]),
}
impl OptionDefault {
/// The owned value this default stands for.
pub fn value(self) -> OptionValue {
match self {
OptionDefault::Bool(b) => OptionValue::Bool(b),
OptionDefault::Int(n) => OptionValue::Int(n),
OptionDefault::Str(s) => OptionValue::Str(s.to_string()),
OptionDefault::List(items) => {
OptionValue::List(items.iter().map(|s| s.to_string()).collect())
}
}
}
/// How the rule reference and the settings UI print this default.
pub fn as_written(self) -> String {
match self {
OptionDefault::Bool(b) => b.to_string(),
OptionDefault::Int(n) => n.to_string(),
OptionDefault::Str(s) => format!("\"{s}\""),
OptionDefault::List(items) => {
let inner: Vec<String> = items.iter().map(|s| format!("\"{s}\"")).collect();
format!("[{}]", inner.join(", "))
}
}
}
}
/// One option a rule declares: its name, its kind, what it is when nobody
/// says otherwise, and what it is for.
#[derive(Debug, Clone, Copy)]
pub struct OptionSpec {
/// The key a user writes, as Verible spells it where there is an
/// equivalent.
pub name: &'static str,
/// What kind of value it takes.
pub kind: OptionKind,
/// The value a rule reads when nobody configured it.
pub default: OptionDefault,
/// One line saying what it does — the text `--rules-doc` prints.
pub doc: &'static str,
}
/// The options a run resolved to: `rule → key → value`, validated.
///
/// Only what somebody actually set is in here. A rule asks for an option it
/// declares and gets the spec's default when this map is silent, which is why
/// no rule has an "unset" case to handle and why an empty map is exactly the
/// shipped behaviour.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleOptions {
values: BTreeMap<(String, String), OptionValue>,
}
/// The options a run with nothing configured has — what a context that was
/// lent none reads from.
static NONE: RuleOptions = RuleOptions::new();
impl RuleOptions {
/// An empty set of options.
pub const fn new() -> RuleOptions {
RuleOptions { values: BTreeMap::new() }
}
/// The shared empty set, for a caller with nothing to configure.
pub(crate) fn none() -> &'static RuleOptions {
&NONE
}
/// Whether anything at all was configured.
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
/// Sets one option from the text a `lucisv.toml` wrote after the `=`.
///
/// The value's shape is read **against the spec's kind** — `true`, `42`,
/// `"text"`, `["a", "b"]` — so the message a user gets names the kind the
/// option actually takes rather than TOML's idea of what they typed.
/// Unlike `lucisv_core::config`'s strings, a backslash is an ordinary
/// character here: a pattern is the one value that needs them.
pub fn set_raw(&mut self, rule: &str, key: &str, raw: &str) -> Result<(), String> {
let spec = spec_of(rule, key)?;
let value = parse_raw(&spec, raw)?;
self.insert(rule, key, value)
}
/// Sets one option from a value a front end already decoded (the editor's
/// JSON). Validated exactly as [`Self::set_raw`]'s is.
pub fn set(&mut self, rule: &str, key: &str, value: OptionValue) -> Result<(), String> {
let spec = spec_of(rule, key)?;
let value = check(&spec, value)?;
self.insert(rule, key, value)
}
fn insert(&mut self, rule: &str, key: &str, value: OptionValue) -> Result<(), String> {
self.values.insert((rule.to_string(), key.to_string()), value);
Ok(())
}
/// Lays `other`'s entries over this set's, key by key.
///
/// The merge the two front ends need: a `lucisv.toml`'s options are the
/// base and the editor's are laid over them one key at a time, so a
/// project that sets two options and a user who overrides one keep the
/// other. Both sides were validated when they were read, so nothing can
/// be refused here.
pub fn overlay(&mut self, other: &RuleOptions) {
for (key, value) in &other.values {
self.values.insert(key.clone(), value.clone());
}
}
/// Whether this run set `key` on `rule` at all — the one question a rule
/// asks when its default is not a constant (`line-length`'s `length`
/// falls back to the formatter's width).
pub fn is_set(&self, rule: &str, key: &str) -> bool {
self.lookup(rule, key).is_some()
}
/// A boolean option's value, or its default.
pub fn bool(&self, rule: &str, key: &str) -> bool {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::Bool(b)), _) => *b,
(_, Some(OptionDefault::Bool(b))) => b,
_ => false,
}
}
/// An integer option's value, or its default.
pub fn int(&self, rule: &str, key: &str) -> i64 {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::Int(n)), _) => *n,
(_, Some(OptionDefault::Int(n))) => n,
_ => 0,
}
}
/// A string (or pattern) option's value, or its default.
pub fn str(&self, rule: &str, key: &str) -> &str {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::Str(s)), _) => s,
(_, Some(OptionDefault::Str(s))) => s,
_ => "",
}
}
/// A list option's value, or its default.
pub fn list(&self, rule: &str, key: &str) -> Vec<String> {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::List(items)), _) => items.clone(),
(_, Some(OptionDefault::List(items))) => {
items.iter().map(|item| item.to_string()).collect()
}
_ => Vec::new(),
}
}
fn lookup(&self, rule: &str, key: &str) -> Option<&OptionValue> {
// A borrowed lookup without allocating the pair: the map is tiny (a
// handful of entries at most), so a scan is cheaper than the two
// `String`s a keyed lookup would build on every rule's every read.
self.values.iter().find(|((r, k), _)| r == rule && k == key).map(|(_, value)| value)
}
}
/// The spec for `rule`'s `key`, or the message a user should read instead.
fn spec_of(rule: &str, key: &str) -> Result<OptionSpec, String> {
let found = rule_by_name(rule).ok_or_else(|| format!("unknown rule `{rule}`"))?;
let options = found.options();
if options.is_empty() {
return Err(format!("rule `{rule}` takes no options"));
}
options.iter().find(|spec| spec.name == key).copied().ok_or_else(|| {
let known = options.iter().map(|spec| spec.name).collect::<Vec<_>>().join(", ");
format!("rule `{rule}` has no option `{key}`; it has: {known}")
})
}
/// One option's declared default, or `None` for a key no rule declares —
/// which the accessors treat as the type's own zero, since nothing can have
/// been stored under it either.
fn default_of(rule: &str, key: &str) -> Option<OptionDefault> {
let found = rule_by_name(rule)?;
found.options().iter().find(|spec| spec.name == key).map(|spec| spec.default)
}
/// Reads `raw` — the text after the `=` in a `lucisv.toml` — as the kind
/// `spec` declares.
fn parse_raw(spec: &OptionSpec, raw: &str) -> Result<OptionValue, String> {
let raw = raw.trim();
let value = match spec.kind {
OptionKind::Bool => match raw {
"true" => OptionValue::Bool(true),
"false" => OptionValue::Bool(false),
_ => return Err(expected(spec, "`true` or `false`", raw)),
},
OptionKind::Int { .. } => {
let digits = raw.strip_prefix('-').unwrap_or(raw);
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return Err(expected(spec, "an integer", raw));
}
let n: i64 = raw.parse().map_err(|_| expected(spec, "an integer", raw))?;
OptionValue::Int(n)
}
OptionKind::Str | OptionKind::Regex | OptionKind::Words(_) => {
OptionValue::Str(unquote(spec, raw)?)
}
OptionKind::List | OptionKind::RegexList => {
let inner = raw
.strip_prefix('[')
.and_then(|rest| rest.strip_suffix(']'))
.ok_or_else(|| expected(spec, "a list like `[\"a\", \"b\"]`", raw))?;
let mut items: Vec<&str> = inner.split(',').map(str::trim).collect();
if items.last() == Some(&"") {
// Either an empty list or a permitted trailing comma.
items.pop();
}
OptionValue::List(
items.iter().map(|item| unquote(spec, item)).collect::<Result<_, _>>()?,
)
}
};
check(spec, value)
}
/// A `"quoted"` string, kept as written — backslashes and all.
fn unquote(spec: &OptionSpec, raw: &str) -> Result<String, String> {
let inner = raw
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.ok_or_else(|| expected(spec, "a quoted string", raw))?;
if inner.contains('"') {
return Err(expected(spec, "a quoted string", raw));
}
Ok(inner.to_string())
}
/// Whether `value` is one this option accepts: the right kind, in range, and
/// — for a pattern — one that compiles.
fn check(spec: &OptionSpec, value: OptionValue) -> Result<OptionValue, String> {
match (spec.kind, &value) {
(OptionKind::Bool, OptionValue::Bool(_)) => Ok(value),
(OptionKind::Int { min, max }, OptionValue::Int(n)) => {
if *n < min || *n > max {
return Err(format!("`{}` must be between {min} and {max}, found {n}", spec.name));
}
Ok(value)
}
(OptionKind::Str, OptionValue::Str(_)) => Ok(value),
(OptionKind::Regex, OptionValue::Str(pattern)) => {
compile(spec, pattern)?;
Ok(value)
}
(OptionKind::List, OptionValue::List(_)) => Ok(value),
(OptionKind::RegexList, OptionValue::List(patterns)) => {
for pattern in patterns {
compile(spec, pattern)?;
}
Ok(value)
}
(OptionKind::Words(vocabulary), OptionValue::Str(spelling)) => {
let words: Vec<&str> = spelling.split('|').map(str::trim).collect();
if words.iter().any(|word| word.is_empty()) {
return Err(format!("`{}`: empty word in `{spelling}`", spec.name));
}
if let Some(bad) = words.iter().find(|word| !vocabulary.contains(word)) {
return Err(format!(
"`{}`: `{bad}` is not one of {}",
spec.name,
vocabulary.join(", ")
));
}
Ok(value)
}
_ => Err(format!(
"`{}` expects {}, found {}",
spec.name,
article(spec.kind),
value.kind_word()
)),
}
}
/// Compiles one pattern, naming the option in the message.
fn compile(spec: &OptionSpec, pattern: &str) -> Result<(), String> {
Regex::compile(pattern)
.map(|_| ())
.map_err(|e| format!("`{}`: `{pattern}` is not a valid pattern: {e}", spec.name))
}
/// The kind, with the article an error message wants in front of it.
fn article(kind: OptionKind) -> String {
match kind {
OptionKind::Int { .. } => "an integer".to_string(),
other => format!("a {}", other.as_str()),
}
}
fn expected(spec: &OptionSpec, wanted: &str, raw: &str) -> String {
format!("`{}` expects {wanted}, found `{raw}`", spec.name)
}
/// A compiled pattern option, or `None` when it does not compile.
///
/// Every pattern a run holds was compiled once when it was accepted, so
/// `None` here can only be a spec whose own default is wrong — which the
/// registry's tests forbid.
pub(crate) fn pattern(options: &RuleOptions, rule: &str, key: &str) -> Option<Regex> {
Regex::compile(options.str(rule, key)).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn options() -> RuleOptions {
RuleOptions::new()
}
#[test]
fn an_unset_option_reads_its_specs_default() {
let opts = options();
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
assert_eq!(opts.int("line-length", "length"), 100);
assert!(!opts.is_set("line-length", "length"));
assert!(opts.is_empty());
}
#[test]
fn a_set_option_wins_and_is_remembered_as_set() {
let mut opts = options();
opts.set_raw("line-length", "length", "120").expect("accepted");
assert_eq!(opts.int("line-length", "length"), 120);
assert!(opts.is_set("line-length", "length"));
assert!(!opts.is_empty());
}
#[test]
fn every_kind_parses_from_the_text_a_toml_writes() {
let mut opts = options();
opts.set_raw("typedef-structs-unions", "allow_anonymous_nested", "true").expect("bool");
assert!(opts.bool("typedef-structs-unions", "allow_anonymous_nested"));
opts.set_raw("signal-name-style", "style_regex", "\"[a-z]+\"").expect("regex");
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z]+");
opts.set_raw("generate-label-prefix", "prefix", "[ \"g_\", \"gen_\", ]").expect("list");
assert_eq!(
opts.list("generate-label-prefix", "prefix"),
vec!["g_".to_string(), "gen_".to_string()]
);
opts.set_raw("port-name-suffix", "suffixes", "[]").expect("empty list");
assert!(opts.list("port-name-suffix", "suffixes").is_empty());
}
#[test]
fn a_backslash_survives_into_a_pattern() {
// `lucisv_core::config` refuses escapes in its own strings; an option
// value is stored raw and read here, which is what lets `\d` through.
let mut opts = options();
opts.set_raw("signal-name-style", "style_regex", "\"[a-z]\\d+\"").expect("accepted");
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z]\\d+");
}
#[test]
fn an_unknown_rule_or_key_says_what_exists() {
let mut opts = options();
let error = opts.set_raw("no-such-rule", "x", "1").err().unwrap_or_default();
assert!(error.contains("unknown rule `no-such-rule`"), "{error}");
let error = opts.set_raw("no-tabs", "width", "4").err().unwrap_or_default();
assert!(error.contains("takes no options"), "{error}");
let error = opts.set_raw("line-length", "len", "120").err().unwrap_or_default();
assert!(error.contains("has no option `len`"), "{error}");
assert!(error.contains("it has: length"), "{error}");
}
#[test]
fn a_wrong_kind_is_refused_through_both_doors() {
let mut opts = options();
assert!(opts.set_raw("line-length", "length", "\"120\"").is_err());
assert!(opts.set_raw("signal-name-style", "style_regex", "120").is_err());
assert!(opts.set_raw("port-name-suffix", "suffixes", "\"_i\"").is_err());
assert!(opts.set_raw("typedef-structs-unions", "allow_anonymous_nested", "yes").is_err());
let error = opts
.set("line-length", "length", OptionValue::Str("120".to_string()))
.err()
.unwrap_or_default();
assert!(error.contains("expects an integer, found a string"), "{error}");
}
#[test]
fn an_out_of_range_integer_is_refused() {
let mut opts = options();
let error = opts.set_raw("line-length", "length", "10").err().unwrap_or_default();
assert!(error.contains("must be between"), "{error}");
assert!(opts.set_raw("line-length", "length", "40").is_ok());
}
/// An escape this engine does not implement is refused when the option
/// is read, not read as a literal — the difference between an error a
/// user can see and a naming rule that quietly judges the wrong names
/// (QA, 2026-09-04).
#[test]
fn an_unsupported_escape_never_becomes_a_literal() {
let mut opts = options();
for pattern in ["\"\\bword\\b\"", "\"(a)\\1\"", "\"\\p{L}+\""] {
let error = opts
.set_raw("signal-name-style", "style_regex", pattern)
.err()
.unwrap_or_else(|| panic!("{pattern} was accepted"));
assert!(error.contains("unsupported escape"), "{pattern}: {error}");
assert!(error.contains("style_regex"), "{pattern}: {error}");
}
// ... and the option keeps its default, so the rule still works.
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
}
#[test]
fn an_invalid_pattern_is_refused_by_name() {
let mut opts = options();
let error =
opts.set_raw("signal-name-style", "style_regex", "\"[a-\"").err().unwrap_or_default();
assert!(error.contains("not a valid pattern"), "{error}");
let error = opts
.set(
"banned-declared-name-patterns",
"patterns",
OptionValue::List(vec!["(ok".to_string()]),
)
.err()
.unwrap_or_default();
assert!(error.contains("not a valid pattern"), "{error}");
}
#[test]
fn a_style_word_outside_the_vocabulary_is_refused() {
let mut opts = options();
assert!(opts
.set_raw("parameter-name-style", "parameter_style", "\"CamelCase|ALL_CAPS\"")
.is_ok());
assert!(opts.set_raw("parameter-name-style", "localparam_style", "\"CamelCase\"").is_ok());
let error = opts
.set_raw("parameter-name-style", "parameter_style", "\"snake_case\"")
.err()
.unwrap_or_default();
assert!(error.contains("is not one of"), "{error}");
let error = opts
.set_raw("parameter-name-style", "parameter_style", "\"CamelCase|\"")
.err()
.unwrap_or_default();
assert!(error.contains("empty word"), "{error}");
}
#[test]
fn a_refused_value_leaves_the_previous_one_standing() {
let mut opts = options();
opts.set_raw("line-length", "length", "120").expect("accepted");
assert!(opts.set_raw("line-length", "length", "2").is_err());
assert_eq!(opts.int("line-length", "length"), 120);
}
/// Key by key: an overlay replaces the keys it names and leaves the
/// rest of the base standing.
#[test]
fn an_overlay_replaces_one_key_at_a_time() {
let mut base = options();
base.set_raw("line-length", "length", "120").expect("accepted");
base.set_raw("generate-label-prefix", "prefix", "[\"blk_\"]").expect("accepted");
let mut top = options();
top.set_raw("line-length", "length", "140").expect("accepted");
base.overlay(&top);
assert_eq!(base.int("line-length", "length"), 140, "the overlay wins");
assert_eq!(
base.list("generate-label-prefix", "prefix"),
vec!["blk_".to_string()],
"and the key it did not name survives"
);
// An empty overlay changes nothing.
base.overlay(&options());
assert_eq!(base.int("line-length", "length"), 140);
}
#[test]
fn defaults_are_written_the_way_a_user_would_type_them() {
assert_eq!(OptionDefault::Bool(true).as_written(), "true");
assert_eq!(OptionDefault::Int(100).as_written(), "100");
assert_eq!(OptionDefault::Str("[a-z]+").as_written(), "\"[a-z]+\"");
assert_eq!(OptionDefault::List(&["g_", "gen_"]).as_written(), "[\"g_\", \"gen_\"]");
assert_eq!(OptionDefault::List(&[]).as_written(), "[]");
}
}
+716
View File
@@ -0,0 +1,716 @@
//! The small regular-expression engine the naming options are spelled with.
//!
//! Verible spells every naming convention as an RE2 pattern, and §34's
//! `style_regex` options are the same patterns typed by the same users, so
//! lucisv has to read them. What it does **not** need is RE2: the patterns
//! that appear in a style guide are character classes, alternation and the
//! three postfix repeats, which is one small engine — and this crate's
//! dependency list (`vlog_parser` + std) is worth more than the syntax nobody
//! writes here.
//!
//! # The supported subset
//!
//! - literals, and `.` for any character except a newline;
//! - `[...]` classes, with `^` negation, `a-z` ranges, a leading `]` or a
//! trailing `-` as a literal, and the `\d`/`\w`/`\s` shorthands inside;
//! - the escapes `\d \D \w \W \s \S` (classes), `\n \t \r` (control
//! characters) and `\<punctuation>` (that character, literally);
//! - groups `( ... )`, alternation `|`, and the postfix `*`, `+`, `?`;
//! - a `^` at the very start and a `$` at the very end, accepted and ignored
//! because the match is **anchored at both ends** anyway: a name matches
//! its style when the whole name matches the pattern, which is how Verible
//! reads its own.
//!
//! **Everything else is refused when the option is read, by name**: counted
//! repetition (`{2,3}`), lookaround (`(?=...)`), and every escape not in the
//! list above — a backreference (`\1`), a word boundary (`\b`), `\A`, `\z`,
//! `\p{...}`, `\x41`. Refusing is the whole point: an unsupported escape
//! treated as a literal would quietly accuse or excuse the wrong names, which
//! is worse than an error the user can read (QA, 2026-09-04).
//!
//! # Why it cannot hang
//!
//! The matcher is a **Thompson NFA simulation** (a Pike VM without capture
//! groups): the pattern is compiled to a small instruction program, and the
//! set of live program counters is advanced one character at a time, each
//! state entered at most once per character. Matching is therefore
//! `O(pattern × name)` **by construction**, whatever shape the pattern has.
//! The backtracking matcher this replaced was exponential on an ambiguous
//! repeat — QA measured `(a*)*b` against a 30-character name at 20.6 s and a
//! guard kill on the shipped binary (2026-09-04), which a user could
//! configure into every future lint run and into every keystroke of an editor
//! session.
/// One compiled pattern, matched whole against a name.
pub(crate) struct Regex {
prog: Vec<Inst>,
}
/// One instruction of the compiled program.
///
/// `Split` and `Jump` are the only control flow, and the only instructions
/// that consume no input; everything else advances one character.
#[derive(Debug, Clone)]
enum Inst {
/// Match this character exactly.
Char(char),
/// Match any character except a newline (`.`).
Any,
/// Match any character of this set.
Class(Class),
/// Continue at **both** targets — the alternation and repeat primitive.
Split(usize, usize),
/// Continue at this target.
Jump(usize),
/// The whole pattern matched, if the input is also finished.
Match,
}
/// A set of characters: ranges, plus an optional negation.
#[derive(Debug, Clone)]
struct Class {
ranges: Vec<(char, char)>,
negated: bool,
}
impl Class {
fn contains(&self, c: char) -> bool {
let hit = self.ranges.iter().any(|(lo, hi)| *lo <= c && c <= *hi);
hit != self.negated
}
}
/// The syntax tree the parser builds and the compiler walks.
enum Node {
/// Matches the empty string.
Empty,
/// One literal character.
Char(char),
/// `.` — any character except a newline.
Any,
/// One `[...]` class, or one of the `\d`-style shorthands.
Class(Class),
/// A sequence, matched left to right.
Concat(Vec<Node>),
/// Alternatives.
Alt(Vec<Node>),
/// A repeated node: `*`, `+` or `?`.
Repeat { node: Box<Node>, kind: RepeatKind },
}
/// Which postfix repeat was written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RepeatKind {
/// `*` — zero or more.
Star,
/// `+` — one or more.
Plus,
/// `?` — zero or one.
Question,
}
impl Regex {
/// Compiles `pattern`, or says what is wrong with it.
pub(crate) fn compile(pattern: &str) -> Result<Regex, String> {
let chars: Vec<char> = pattern.chars().collect();
let mut parser = Parser { chars, at: 0 };
// `^ ... $` is how the same convention is often written down; the
// match is anchored either way, so the anchors are accepted and
// dropped rather than rejected as unsupported.
if parser.chars.first() == Some(&'^') {
parser.at = 1;
}
if parser.chars.last() == Some(&'$') && parser.chars.len() > parser.at && !escaped(&parser)
{
parser.chars.pop();
}
let root = parser.alternation()?;
if let Some(left) = parser.chars.get(parser.at) {
return Err(match left {
')' => "unmatched `)`".to_string(),
c => format!("unexpected `{c}`"),
});
}
let mut prog = Vec::new();
emit(&root, &mut prog);
prog.push(Inst::Match);
Ok(Regex { prog })
}
/// Whether the **whole** of `text` matches the pattern.
///
/// One pass over the characters, carrying the set of live program
/// counters: every state is entered at most once per character, so the
/// cost is `O(prog × text)` however ambiguous the pattern is.
pub(crate) fn is_match(&self, text: &str) -> bool {
let mut current: Vec<usize> = Vec::with_capacity(self.prog.len());
let mut next: Vec<usize> = Vec::with_capacity(self.prog.len());
let mut on_current = vec![false; self.prog.len()];
let mut on_next = vec![false; self.prog.len()];
self.add(0, &mut current, &mut on_current);
for c in text.chars() {
next.clear();
on_next.iter_mut().for_each(|seen| *seen = false);
for &pc in &current {
let takes = match &self.prog[pc] {
Inst::Char(want) => *want == c,
Inst::Any => c != '\n',
Inst::Class(class) => class.contains(c),
// `Match` mid-input is a pattern that ended before the
// name did, which a whole-name match refuses.
Inst::Match | Inst::Split(..) | Inst::Jump(_) => false,
};
if takes {
self.add(pc + 1, &mut next, &mut on_next);
}
}
std::mem::swap(&mut current, &mut next);
std::mem::swap(&mut on_current, &mut on_next);
if current.is_empty() {
return false;
}
}
current.iter().any(|pc| matches!(self.prog[*pc], Inst::Match))
}
/// Adds a thread at `pc`, following the instructions that consume no
/// input. `seen` keeps each state to one visit per character, which is
/// what bounds the work — and what makes a loop of empty matches
/// terminate instead of spinning.
fn add(&self, pc: usize, list: &mut Vec<usize>, seen: &mut [bool]) {
if seen.get(pc).copied().unwrap_or(true) {
return;
}
seen[pc] = true;
match self.prog[pc] {
Inst::Jump(to) => self.add(to, list, seen),
Inst::Split(a, b) => {
self.add(a, list, seen);
self.add(b, list, seen);
}
_ => list.push(pc),
}
}
}
/// Compiles one node onto the end of `prog`.
fn emit(node: &Node, prog: &mut Vec<Inst>) {
match node {
Node::Empty => {}
Node::Char(c) => prog.push(Inst::Char(*c)),
Node::Any => prog.push(Inst::Any),
Node::Class(class) => prog.push(Inst::Class(class.clone())),
Node::Concat(parts) => parts.iter().for_each(|part| emit(part, prog)),
Node::Alt(branches) => emit_alt(branches, prog),
Node::Repeat { node, kind } => emit_repeat(node, *kind, prog),
}
}
/// `split L1, L2; L1: first; jmp end; L2: rest…; end:`
fn emit_alt(branches: &[Node], prog: &mut Vec<Inst>) {
let Some((first, rest)) = branches.split_first() else { return };
if rest.is_empty() {
emit(first, prog);
return;
}
let split = prog.len();
prog.push(Inst::Split(0, 0)); // patched below
emit(first, prog);
let jump = prog.len();
prog.push(Inst::Jump(0)); // patched below
let second = prog.len();
emit_alt(rest, prog);
let end = prog.len();
prog[split] = Inst::Split(split + 1, second);
prog[jump] = Inst::Jump(end);
}
/// The three postfix repeats, each as a split around the body.
fn emit_repeat(node: &Node, kind: RepeatKind, prog: &mut Vec<Inst>) {
match kind {
// L: split body, end; body: … ; jmp L; end:
RepeatKind::Star => {
let split = prog.len();
prog.push(Inst::Split(0, 0));
emit(node, prog);
prog.push(Inst::Jump(split));
let end = prog.len();
prog[split] = Inst::Split(split + 1, end);
}
// body: … ; split body, end; end:
RepeatKind::Plus => {
let body = prog.len();
emit(node, prog);
let split = prog.len();
prog.push(Inst::Split(body, split + 1));
}
// split body, end; body: … ; end:
RepeatKind::Question => {
let split = prog.len();
prog.push(Inst::Split(0, 0));
emit(node, prog);
let end = prog.len();
prog[split] = Inst::Split(split + 1, end);
}
}
}
/// Whether the pattern's last character is escaped — so a trailing `\$` is
/// the literal dollar it was written as and not the anchor.
fn escaped(parser: &Parser) -> bool {
let before = parser.chars.len().saturating_sub(1);
parser.chars[..before].iter().rev().take_while(|c| **c == '\\').count() % 2 == 1
}
/// The escapes this engine understands, for the message a refusal prints.
const SUPPORTED_ESCAPES: &str =
"\\d \\D \\w \\W \\s \\S \\n \\t \\r, and \\<punctuation> for that character";
/// The recursive-descent parser for the subset.
struct Parser {
chars: Vec<char>,
at: usize,
}
impl Parser {
fn peek(&self) -> Option<char> {
self.chars.get(self.at).copied()
}
fn bump(&mut self) -> Option<char> {
let c = self.peek();
self.at += c.is_some() as usize;
c
}
/// `branch ( '|' branch )*`
fn alternation(&mut self) -> Result<Node, String> {
let mut branches = vec![self.concatenation()?];
while self.peek() == Some('|') {
self.at += 1;
branches.push(self.concatenation()?);
}
Ok(if branches.len() == 1 {
branches.pop().unwrap_or(Node::Empty)
} else {
Node::Alt(branches)
})
}
/// `repeated*`, stopping at `|` or the group's `)`.
fn concatenation(&mut self) -> Result<Node, String> {
let mut parts = Vec::new();
while !matches!(self.peek(), None | Some('|') | Some(')')) {
parts.push(self.repeated()?);
}
Ok(match parts.len() {
0 => Node::Empty,
1 => parts.pop().unwrap_or(Node::Empty),
_ => Node::Concat(parts),
})
}
/// One atom with its postfix `*`, `+` or `?`.
fn repeated(&mut self) -> Result<Node, String> {
let atom = self.atom()?;
let kind = match self.peek() {
Some('*') => RepeatKind::Star,
Some('+') => RepeatKind::Plus,
Some('?') => RepeatKind::Question,
_ => return Ok(atom),
};
self.at += 1;
if matches!(self.peek(), Some('*' | '+' | '?')) {
return Err(format!("`{}` cannot follow a repeat", self.peek().unwrap_or('?')));
}
Ok(Node::Repeat { node: Box::new(atom), kind })
}
fn atom(&mut self) -> Result<Node, String> {
match self.bump() {
Some('(') => {
// `(?...)` is lookaround or a flag group — RE2 syntax this
// engine does not implement, and refusing it by name is what
// stops it being read as a literal `?`.
if self.peek() == Some('?') {
return Err(
"`(?...)` groups (lookaround, flags, non-capturing) are unsupported in \
lucisv patterns"
.to_string(),
);
}
let inner = self.alternation()?;
if self.bump() != Some(')') {
return Err("unmatched `(`".to_string());
}
Ok(inner)
}
Some('[') => self.class(),
Some('.') => Ok(Node::Any),
Some('\\') => self.escape(),
Some(c @ ('*' | '+' | '?')) => Err(format!("`{c}` has nothing to repeat")),
Some(c @ ('{' | '}')) => {
Err(format!("`{c}` (counted repetition) is unsupported in lucisv patterns"))
}
Some(c @ ('^' | '$')) => {
Err(format!("`{c}` is only accepted at the start or end of a pattern"))
}
Some(')') => Err("unmatched `)`".to_string()),
Some(c) => Ok(Node::Char(c)),
None => Err("pattern ends where a character was expected".to_string()),
}
}
/// `\d`, `\w`, `\s`, their negations, the three control characters, or a
/// punctuation character escaped to itself.
///
/// **Anything else is an error.** A letter or digit escape this engine
/// does not implement — `\b`, `\A`, `\1`, `\p` — is a pattern from
/// another dialect that would mean something quite different if it were
/// read as a literal, so it is named and refused.
fn escape(&mut self) -> Result<Node, String> {
let c = self.bump().ok_or("a `\\` at the end of the pattern escapes nothing")?;
Ok(match c {
'd' => Node::Class(digits(false)),
'D' => Node::Class(digits(true)),
'w' => Node::Class(word(false)),
'W' => Node::Class(word(true)),
's' => Node::Class(space(false)),
'S' => Node::Class(space(true)),
'n' => Node::Char('\n'),
't' => Node::Char('\t'),
'r' => Node::Char('\r'),
other if other.is_alphanumeric() => return Err(unsupported_escape(other)),
other => Node::Char(other),
})
}
/// A `[...]` class, the `[` already consumed.
fn class(&mut self) -> Result<Node, String> {
let negated = self.peek() == Some('^');
self.at += negated as usize;
let mut ranges: Vec<(char, char)> = Vec::new();
// A `]` written first is a literal `]`, as in every regex dialect.
let mut first = true;
loop {
let c = match self.bump() {
Some(']') if !first => break,
Some(c) => c,
None => return Err("unmatched `[`".to_string()),
};
first = false;
let lo = if c == '\\' { self.class_escape(&mut ranges)? } else { Some(c) };
let Some(lo) = lo else { continue };
// `a-z`, but a `-` before the closing `]` is a literal `-`.
if self.peek() == Some('-') && self.chars.get(self.at + 1) != Some(&']') {
self.at += 1;
let hi = match self.bump() {
Some('\\') => self.class_literal_escape()?,
Some(c) => c,
None => return Err("unmatched `[`".to_string()),
};
if hi < lo {
return Err(format!("class range `{lo}-{hi}` runs backwards"));
}
ranges.push((lo, hi));
} else {
ranges.push((lo, lo));
}
}
if ranges.is_empty() {
return Err("empty character class".to_string());
}
Ok(Node::Class(Class { ranges, negated }))
}
/// An escape inside a class: a shorthand adds its ranges and yields
/// nothing, an escaped punctuation or control character yields itself,
/// and anything else is refused by name.
///
/// The **negated** shorthands (`\D`, `\W`, `\S`) are refused inside a
/// class rather than accepted: a class is one set of ranges with one
/// negation flag, and mixing a complemented set into it would need set
/// arithmetic this engine does not do. Refusing says so; accepting would
/// have to guess.
fn class_escape(&mut self, ranges: &mut Vec<(char, char)>) -> Result<Option<char>, String> {
let c = self.bump().ok_or("a `\\` at the end of a class escapes nothing")?;
let shorthand = match c {
'd' => Some(digits(false)),
'w' => Some(word(false)),
's' => Some(space(false)),
_ => None,
};
if let Some(class) = shorthand {
ranges.extend(class.ranges);
return Ok(None);
}
Ok(Some(match c {
'n' => '\n',
't' => '\t',
'r' => '\r',
'D' | 'W' | 'S' => {
return Err(format!(
"`\\{c}` is unsupported inside a `[...]` class; write it outside one"
))
}
other if other.is_alphanumeric() => return Err(unsupported_escape(other)),
other => other,
}))
}
/// The far end of a class range, which must be one character — a
/// shorthand there (`[a-\d]`) is meaningless.
fn class_literal_escape(&mut self) -> Result<char, String> {
let c = self.bump().ok_or("a `\\` at the end of a class escapes nothing")?;
Ok(match c {
'n' => '\n',
't' => '\t',
'r' => '\r',
other if other.is_alphanumeric() => return Err(unsupported_escape(other)),
other => other,
})
}
}
/// The one message an unimplemented escape gets, wherever it was written.
fn unsupported_escape(c: char) -> String {
format!("unsupported escape `\\{c}` (supported: {SUPPORTED_ESCAPES})")
}
fn digits(negated: bool) -> Class {
Class { ranges: vec![('0', '9')], negated }
}
fn word(negated: bool) -> Class {
Class { ranges: vec![('a', 'z'), ('A', 'Z'), ('0', '9'), ('_', '_')], negated }
}
fn space(negated: bool) -> Class {
Class { ranges: vec![(' ', ' '), ('\t', '\t'), ('\n', '\n'), ('\r', '\r')], negated }
}
#[cfg(test)]
mod tests {
use super::*;
fn hit(pattern: &str, text: &str) -> bool {
Regex::compile(pattern).unwrap_or_else(|e| panic!("{pattern}: {e}")).is_match(text)
}
#[test]
fn the_patterns_the_naming_options_ship_with_work() {
// Every default this round introduces, against real names.
assert!(hit("[a-z_0-9]+", "wr_en"));
assert!(!hit("[a-z_0-9]+", "wrEn"));
assert!(hit("[a-z_0-9]+(_if)", "bus_if"));
assert!(!hit("[a-z_0-9]+(_if)", "bus"));
assert!(hit("[A-Z_0-9]+", "MY_MACRO"));
assert!(!hit("[A-Z_0-9]+", "my_macro"));
assert!(hit("([a-z0-9]+_)+c", "addr_range_c"));
assert!(!hit("([a-z0-9]+_)+c", "addr_range"));
assert!(hit("[a-z_0-9]+(_t|_e)", "state_e"));
assert!(hit("[a-z_0-9]+(_t|_e)", "word_t"));
assert!(!hit("[a-z_0-9]+(_t|_e)", "word"));
}
/// The probe table, every verdict checked against Python's
/// `re.fullmatch` (QA's 46 probes of 2026-09-04 plus this round's own).
/// It is written down rather than described so a change to the engine
/// has to disagree with CPython in public.
#[test]
fn every_probe_agrees_with_python_re_fullmatch() {
// (pattern, text, re.fullmatch(pattern, text) is not None)
let probes: &[(&str, &str, bool)] = &[
// literals and anchoring
("abc", "abc", true),
("abc", "abcd", false),
("abc", "xabcx", false),
("abc", "ab", false),
("", "", true),
("", "a", false),
// `.`
("a.c", "abc", true),
("a.c", "a_c", true),
("a.c", "ac", false),
(".*", "anything", true),
("a.b", "a\nb", false),
// classes
("[a-z]+", "abc", true),
("[a-z]+", "abC", false),
("[a-z_0-9]+", "a_1", true),
("[^0-9]+", "abc", true),
("[^0-9]+", "ab1", false),
("[a-]+", "a-a", true),
("[]a]+", "]a", true),
("[\\]]", "]", true),
("[a-c-e]+", "a-e", true),
("[A-Za-z][A-Za-z0-9]*", "Ab9", true),
("[A-Za-z][A-Za-z0-9]*", "9Ab", false),
// shorthands
("\\d+", "42", true),
("\\d+", "4a", false),
("\\D+", "abc", true),
("\\D+", "ab1", false),
("\\w+", "a_1", true),
("\\w+", "a-1", false),
("\\W+", "-", true),
("\\W+", "a", false),
("\\s+", " \t", true),
("\\s+", " a", false),
("\\S+", "abc", true),
("[\\d_]+", "4_2", true),
("[\\w]+", "a_1", true),
("a\\.b", "a.b", true),
("a\\.b", "axb", false),
// groups, alternation, nesting
("(a|b)(c|d)", "ad", true),
("(a|b)(c|d)", "ac", true),
("(a|b)(c|d)", "bb", false),
("(ab|a)+b", "aab", true),
("((a|b)+_)?x", "abab_x", true),
("((a|b)+_)?x", "x", true),
("(a|)b", "b", true),
("(|a)b", "ab", true),
("(ab)+", "ababab", true),
("(ab)+", "ababa", false),
// repeats, including the ambiguous shapes that used to blow up
("a*ab", "aaab", true),
("a+b", "b", false),
("a?b", "b", true),
("(a?)*b", "b", true),
("(a*)*b", "aaab", true),
("(a*)*b", "aaaa", false),
("(a|aa)*b", "aaaab", true),
("(a|aa)*b", "aaaa", false),
("(.*)*x", "abcx", true),
("(.*)*x", "abc", false),
("((a*)*)*b", "aab", true),
("(a+)+b", "aaab", true),
("(a+)+b", "aaa", false),
// the shipped defaults, both ways
("[a-z][a-z_0-9]*(_t|_e)", "state_e", true),
("[a-z][a-z_0-9]*(_t|_e)", "_state_e", false),
("[a-z][a-z_0-9]*_t", "word_t", true),
("[a-z][a-z_0-9]*_t", "wordt", false),
("[a-z_0-9]+(_if)", "clk_rst_if", true),
("[a-z_0-9]+(_if)", "bus_intf", false),
("([a-z0-9]+_)+c", "addr_range_c", true),
("([a-z0-9]+_)+c", "c", false),
("[A-Z_0-9]+", "W2", true),
("[a-z][a-z_0-9]*", "fifo2_ctrl", true),
("[a-z][a-z_0-9]*", "Fifo2Ctrl", false),
];
for (pattern, text, expected) in probes {
assert_eq!(hit(pattern, text), *expected, "{pattern:?} vs {text:?}");
}
assert!(probes.len() >= 60, "the table is the pin; keep it wide");
}
#[test]
fn the_match_is_anchored_at_both_ends() {
assert!(!hit("[a-z]+", "abc1"));
assert!(!hit("bc", "abc"));
assert!(hit("^[a-z]+$", "abc"), "explicit anchors are accepted and ignored");
assert!(hit("a\\$", "a$"), "an escaped `$` at the end is a literal");
}
/// The HIGH finding of 2026-09-04: an ambiguous repeat was exponential
/// under the old backtracking matcher (30 characters took 20.6 s and hit
/// the runaway guard). The NFA simulation is linear by construction, so
/// the same shapes finish on a 200-character name in microseconds.
#[test]
fn an_ambiguous_repeat_is_linear_not_exponential() {
let long = "a".repeat(200);
let start = std::time::Instant::now();
for pattern in ["(a*)*b", "(a|aa)*b", "(.*)*x", "((a*)*)*b", "(a+)+b", "(a?)*b"] {
assert!(!hit(pattern, &long), "{pattern} must not match a name of only `a`s");
}
let elapsed = start.elapsed();
assert!(
elapsed < std::time::Duration::from_millis(500),
"six ambiguous patterns over 200 characters took {elapsed:?}; \
the matcher is backtracking again"
);
}
/// An unsupported escape is refused **by name**, never read as a
/// literal — the second HIGH finding of 2026-09-04. QA's two cases are
/// the first two rows.
#[test]
fn an_unsupported_escape_is_refused_by_name() {
for pattern in [
"(a)\\1", // a backreference: must not match `a1`
"\\bword\\b", // a word boundary: must not match `bwordb`
"\\B",
"\\A",
"\\z",
"\\Z",
"\\p{L}",
"\\x41",
"\\u0041",
"\\Q",
"\\9",
"\\0",
"\\f",
"\\v",
"[\\b]",
"[a\\1]",
"[a-\\d]",
"[\\D]",
"[\\S]",
"[\\W]",
] {
let error = Regex::compile(pattern).err().unwrap_or_else(|| {
panic!("{pattern} compiled; an unimplemented escape must be refused")
});
assert!(
error.contains("unsupported") || error.contains("unsupported inside"),
"{pattern}: {error}"
);
}
// The message names the escape and what is available instead.
let error = Regex::compile("\\bword\\b").err().unwrap_or_default();
assert!(error.contains("`\\b`"), "{error}");
assert!(error.contains("\\d"), "{error}");
// And the supported ones still compile.
for pattern in [
"\\d", "\\D", "\\w", "\\W", "\\s", "\\S", "\\n", "\\t", "\\r", "\\.", "\\\\", "\\[",
"\\]", "\\(", "\\)", "\\|", "\\+", "\\*", "\\?", "\\-", "\\{", "\\}", "\\^", "\\$",
"[\\d]", "[\\w]", "[\\s]", "[\\-]",
] {
assert!(Regex::compile(pattern).is_ok(), "{pattern} must compile");
}
}
#[test]
fn a_bad_pattern_says_what_is_wrong() {
for (pattern, wanted) in [
("(a", "unmatched `("),
("a)", "unmatched `)`"),
("[a", "unmatched `["),
("[]", "unmatched `["),
("[^]", "unmatched `["),
("*a", "nothing to repeat"),
("a**", "cannot follow a repeat"),
("a{2}", "counted repetition"),
("a{2,3}", "counted repetition"),
("(?=a)b", "(?...)"),
("(?:a)b", "(?...)"),
("a$b", "start or end"),
("[z-a]", "runs backwards"),
("a\\", "escapes nothing"),
] {
let error = Regex::compile(pattern).err().unwrap_or_default();
assert!(error.contains(wanted), "{pattern}: {error}");
}
}
#[test]
fn unicode_passes_through_as_literals() {
assert!(hit("naïve", "naïve"));
assert!(!hit("[a-z]+", "naïve"));
// A non-ASCII letter escape is still an escape nobody implements.
assert!(Regex::compile("\\é").is_err());
}
}
+92
View File
@@ -1,6 +1,7 @@
//! The rule trait and the table of rules that exist.
use crate::context::LintContext;
use crate::options::OptionSpec;
use crate::rules;
use crate::severity::Severity;
use crate::violation::{Applicability, Violation};
@@ -59,6 +60,18 @@ pub trait Rule: Sync {
None
}
/// What a user may configure about this rule, or nothing.
///
/// The keys are Verible's wherever it has the same option, so a project
/// migrating a `.rules.verible` file types the same words. A rule reads
/// one through [`LintContext`], never from a run's settings directly, and
/// always gets a value: the spec's default is the fallback, so there is no
/// "unset" case in any rule. See
/// `docs/features/linter-expansion-2/README.md`.
fn options(&self) -> &'static [OptionSpec] {
&[]
}
/// Everything this rule finds in one file.
fn check(&self, ctx: &LintContext) -> Vec<Violation>;
}
@@ -66,19 +79,29 @@ pub trait Rule: Sync {
/// Every rule that exists, in a stable order.
pub fn all_rules() -> Vec<&'static dyn Rule> {
vec![
&rules::always_comb::AlwaysComb,
&rules::always_comb_blocking::AlwaysCombBlocking,
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
&rules::banned_declared_name_patterns::BannedDeclaredNamePatterns,
&rules::case_missing_default::CaseMissingDefault,
&rules::constraint_name_style::ConstraintNameStyle,
&rules::duplicate_declaration::DuplicateDeclaration,
&rules::empty_item::EmptyItem,
&rules::enum_name_style::EnumNameStyle,
&rules::explicit_begin::ExplicitBegin,
&rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType,
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
&rules::forbid_consecutive_null_statements::ForbidConsecutiveNullStatements,
&rules::forbid_defparam::ForbidDefparam,
&rules::forbid_negative_array_dim::ForbidNegativeArrayDim,
&rules::generate_label::GenerateLabel,
&rules::generate_label_prefix::GenerateLabelPrefix,
&rules::incomplete_assignment::IncompleteAssignment,
&rules::instance_shadowing::InstanceShadowing,
&rules::interface_name_style::InterfaceNameStyle,
&rules::invalid_system_task_function::InvalidSystemTaskFunction,
&rules::line_length::LineLength,
&rules::macro_name_style::MacroNameStyle,
&rules::mismatched_labels::MismatchedLabels,
&rules::module_filename::ModuleFilename,
&rules::module_name_style::ModuleNameStyle,
@@ -87,12 +110,20 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
&rules::multiply_driven::MultiplyDriven,
&rules::no_tabs::NoTabs,
&rules::no_trailing_whitespace::NoTrailingWhitespace,
&rules::one_module_per_file::OneModulePerFile,
&rules::package_filename::PackageFilename,
&rules::packed_dimensions_range_ordering::PackedDimensionsRangeOrdering,
&rules::parameter_name_style::ParameterNameStyle,
&rules::parameter_type_name_style::ParameterTypeNameStyle,
&rules::plusarg_assignment::PlusargAssignment,
&rules::port_name_suffix::PortNameSuffix,
&rules::posix_eof::PosixEof,
&rules::signal_name_style::SignalNameStyle,
&rules::struct_union_name_style::StructUnionNameStyle,
&rules::suspicious_semicolon::SuspiciousSemicolon,
&rules::truncated_numeric_literal::TruncatedNumericLiteral,
&rules::typedef_enums::TypedefEnums,
&rules::typedef_structs_unions::TypedefStructsUnions,
&rules::undeclared_identifier::UndeclaredIdentifier,
&rules::undersized_binary_literal::UndersizedBinaryLiteral,
&rules::undriven_net::UndrivenNet,
@@ -427,6 +458,67 @@ mod tests {
assert!(message.contains("no-tabs"), "{message}");
}
/// Every option a rule declares is one a user could actually write down,
/// and one whose own default is acceptable to itself — a default outside
/// its range, or a pattern that does not compile, would be a rule nobody
/// could satisfy.
#[test]
fn every_declared_option_is_well_formed() {
use crate::options::{OptionKind, RuleOptions};
for rule in all_rules() {
let mut names: Vec<&str> = rule.options().iter().map(|spec| spec.name).collect();
let count = names.len();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), count, "{}: duplicate option names", rule.name());
for spec in rule.options() {
let where_ = format!("{}.{}", rule.name(), spec.name);
assert!(
spec.name.chars().all(|c| c.is_ascii_lowercase()
|| c.is_ascii_digit()
|| c == '_'
|| c == '-'),
"{where_}: option names are lower-case words",
);
assert!(spec.doc.len() > 10, "{where_}: doc too thin");
assert!(!spec.doc.ends_with('.'), "{where_}: doc ends in a period");
let mut options = RuleOptions::new();
options
.set(rule.name(), spec.name, spec.default.value())
.unwrap_or_else(|e| panic!("{where_}: its own default is refused: {e}"));
if let OptionKind::Int { min, max } = spec.kind {
assert!(min <= max, "{where_}: empty range");
}
}
}
}
/// The options §34 gave the four naming rules that predate them, spelled
/// as Verible spells the same options.
#[test]
fn the_naming_rules_take_the_options_verible_gives_them() {
let names = |rule: &str| {
rule_by_name(rule)
.unwrap_or_else(|| panic!("{rule} exists"))
.options()
.iter()
.map(|spec| spec.name)
.collect::<Vec<_>>()
};
assert_eq!(names("enum-name-style"), vec!["style_regex"]);
assert_eq!(names("struct-union-name-style"), vec!["style_regex"]);
assert_eq!(names("module-name-style"), vec!["style_regex"]);
assert_eq!(
names("parameter-name-style"),
vec![
"localparam_style",
"localparam_style_regex",
"parameter_style",
"parameter_style_regex"
]
);
}
#[test]
fn lookup_by_name_finds_every_rule_and_nothing_else() {
for rule in all_rules() {
+85 -3
View File
@@ -6,8 +6,10 @@
//! per rule. If a rule exists, it is in here; if its `doc` changes, so does
//! this.
use crate::options::OptionKind;
use crate::registry::all_rules;
use crate::severity::Severity;
use crate::Rule;
/// The whole rule reference as one markdown document.
pub fn rules_markdown() -> String {
@@ -30,7 +32,13 @@ pub fn rules_markdown() -> String {
a stdin buffer it is off and must be selected. Any rule can be turned \
off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive \
<name>`.\n\n",
<name>`.\n\n\
A rule with **options** is configured in a `[lint.<rule-name>]` \
table of a `lucisv.toml`, or from an editor with \
`lucisv.lint.options`; an option nobody sets reads the default \
listed with it. An unknown option name, a value of the wrong kind, \
an integer out of range and a pattern that does not compile are all \
refused, naming the file and the line.\n\n",
);
out.push_str("| Rule | Severity | Default | Fix |\n|---|---|---|---|\n");
@@ -58,11 +66,44 @@ pub fn rules_markdown() -> String {
));
out.push_str(rule.doc());
out.push_str("\n\n");
out.push_str(&options_table(rule));
}
}
out
}
/// A rule's options, as a small table under its prose — empty for a rule
/// that takes none, which is most of them.
fn options_table(rule: &dyn Rule) -> String {
if rule.options().is_empty() {
return String::new();
}
let mut out = String::from("| Option | Kind | Default | Meaning |\n|---|---|---|---|\n");
for spec in rule.options() {
out.push_str(&format!(
"| `{name}` | {kind} | `{default}` | {doc} |\n",
name = spec.name,
kind = kind_word(spec.kind),
default = spec.default.as_written(),
doc = spec.doc,
));
}
out.push('\n');
out
}
/// How the reference spells an option's kind, a `Words` option's vocabulary
/// included — a user cannot guess `CamelCase|ALL_CAPS` from "word list".
fn kind_word(kind: OptionKind) -> String {
match kind {
OptionKind::Int { min, max } => format!("integer {min}–{max}"),
OptionKind::Words(vocabulary) => {
format!("one or more of {} joined with `\\|`", vocabulary.join(", "))
}
other => other.as_str().to_string(),
}
}
/// How the table spells a rule's default: on, off, or on wherever there is a
/// project to ask about ([`crate::Rule::needs_workspace`]).
fn default_word(rule: &dyn crate::Rule) -> &'static str {
@@ -171,13 +212,47 @@ mod tests {
}
}
/// Every option a rule declares is in the reference, with the default a
/// run that configures nothing actually reads.
#[test]
fn every_option_is_listed_with_its_kind_and_default() {
let markdown = rules_markdown();
for rule in all_rules() {
for spec in rule.options() {
assert!(
markdown.contains(&format!("| `{}` |", spec.name)),
"{}.{}",
rule.name(),
spec.name
);
assert!(markdown.contains(spec.doc), "{}.{}: doc", rule.name(), spec.name);
}
}
assert!(markdown.contains("| `length` | integer 40–400 | `100` |"), "line-length");
assert!(
markdown.contains("| `prefix` | list of strings | `[\"g_\", \"gen_\"]` |"),
"generate-label-prefix"
);
assert!(
markdown.contains("one or more of CamelCase, ALL_CAPS joined with"),
"parameter-name-style's vocabulary"
);
// A rule with no options gets no table.
let no_tabs = markdown
.split("## no-tabs\n")
.nth(1)
.and_then(|rest| rest.split("\n## ").next())
.unwrap_or_default();
assert!(!no_tabs.contains("| Option |"), "{no_tabs}");
}
#[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(10).collect();
let head: Vec<&str> = markdown.lines().take(12).collect();
assert_eq!(
head,
vec![
@@ -200,6 +275,12 @@ mod tests {
rule can be turned off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive <name>`.",
"",
"A rule with **options** is configured in a `[lint.<rule-name>]` table of a \
`lucisv.toml`, or from an editor with `lucisv.lint.options`; an option nobody \
sets reads the default listed with it. An unknown option name, a value of the \
wrong kind, an integer out of range and a pattern that does not compile are \
all refused, naming the file and the line.",
"",
"| Rule | Severity | Default | Fix |",
"|---|---|---|---|",
]
@@ -209,12 +290,13 @@ mod tests {
.find(|rule| rule.severity() == Severity::Error)
.expect("some rule is an error");
let section = format!(
"## {}\n\n{}.\n\n- Severity: error\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),
fix_word(first_rule),
first_rule.doc(),
options_table(first_rule),
);
assert!(markdown.contains(&section), "per-rule section shape changed:\n{section}");
assert!(markdown.ends_with("\n\n"));
+164
View File
@@ -0,0 +1,164 @@
//! `always-comb` — write combinational logic as `always_comb`.
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, SensList, StmtKind, TimingControl};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct AlwaysComb;
const NAME: &str = "always-comb";
impl Rule for AlwaysComb {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"write `always_comb` instead of `always @*`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"`always_comb` says what the block is *for*, and the language checks \
the claim: the tool errors if anything else drives one of its \
left-hand sides, and it infers the sensitivity list including the \
functions the block calls — which `always @*` does not. Verible's \
`always-comb` (enabled by default) asks for the SystemVerilog \
spelling wherever `always @*` or `always @(*)` is written, and lucisv \
checks the same thing.\n\n\
The fix is offered but **unsafe**, and the reason is real: an \
`always_comb` block runs once at time zero and an `always @*` block \
does not run until something in its sensitivity list changes, so a \
testbench that samples before the first change can see a different \
value. It also becomes an error for the block's outputs to be driven \
anywhere else, which is usually the bug being found but is still a \
change in what compiles. `--unsafe-fixes` applies it; the edit is the \
keyword and its `@(*)`, nothing else."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Unsafe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Always { kw, stmt } = &item.kind else { return };
if kw != "always" {
return;
}
let StmtKind::Timing { control: TimingControl::Event(sens), stmt: Some(body) } =
&stmt.kind
else {
return;
};
if !matches!(sens, SensList::Star { .. }) {
return;
}
let Some(header) = header_span(ctx, item.span.start, body.span.start) else { return };
out.push(
Violation::new(NAME, "use `always_comb` instead of `always @*`", header)
.with_fix(Fix::unsafe_fix(vec![(header, "always_comb".to_string())])),
);
});
out
}
}
/// The `always @(*)` in front of the body: from the keyword to the end of the
/// last token before the body starts.
///
/// Read off the tokens rather than assumed, because the sensitivity control
/// may be written `@*`, `@ (*)` or `@( /* why */ * )`, and the fix must
/// replace exactly what was written and not a byte more.
fn header_span(ctx: &LintContext, start: u32, body: u32) -> Option<TextRange> {
let end = ctx
.tokens()
.iter()
.filter(|token| token.span.start >= start && token.span.end <= body)
.map(|token| token.span.end)
.max()?;
(end > start).then(|| TextRange::new(start, end))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
AlwaysComb.check(&LintContext::new(src, None))
}
#[test]
fn flags_both_spellings_and_rewrites_only_the_header() {
for src in [
"module m;\n always @(*) x = 1;\nendmodule\n",
"module m;\n always @* x = 1;\nendmodule\n",
] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}");
let fixed = apply_fixes(src, &found, true);
assert_eq!(fixed.output, "module m;\n always_comb x = 1;\nendmodule\n", "{src}");
}
}
#[test]
fn the_fix_is_unsafe() {
let src = "module m;\n always @(*) x = 1;\nendmodule\n";
let found = violations(src);
assert_eq!(found[0].fix.as_ref().map(|f| f.applicability), Some(Applicability::Unsafe));
assert_eq!(apply_fixes(src, &found, false).applied, 0, "not without --unsafe-fixes");
}
#[test]
fn a_multi_line_block_keeps_its_layout() {
let src = "module m;\n always @(*) begin\n x = 1;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(
apply_fixes(src, &found, true).output,
"module m;\n always_comb begin\n x = 1;\n end\nendmodule\n"
);
}
#[test]
fn a_comment_inside_the_control_is_replaced_with_it() {
// The whole header is one edit, so a comment written inside `@( * )`
// goes with it — which is why the fix is offered, not applied.
let src = "module m;\n always @( /* all */ * ) x = 1;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(
apply_fixes(src, &found, true).output,
"module m;\n always_comb x = 1;\nendmodule\n"
);
}
#[test]
fn an_explicit_sensitivity_list_is_none_of_its_business() {
for src in [
"module m;\n always @(a or b) x = 1;\nendmodule\n",
"module m;\n always @(posedge clk) q <= d;\nendmodule\n",
"module m;\n always_comb x = 1;\nendmodule\n",
"module m;\n always_ff @(posedge clk) q <= d;\nendmodule\n",
"module m;\n always @(*);\nendmodule\n",
] {
assert!(violations(src).is_empty(), "{src}");
}
}
#[test]
fn an_always_star_inside_a_generate_block_is_covered() {
let src = "module m;\n if (A) begin : g\n always @(*) x = 1;\n end\nendmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
}
@@ -0,0 +1,139 @@
//! `banned-declared-name-patterns` — names a project has forbidden.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::regex::Regex;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
/// See [`Rule::doc`].
pub struct BannedDeclaredNamePatterns;
const NAME: &str = "banned-declared-name-patterns";
impl Rule for BannedDeclaredNamePatterns {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not declare a name the project has banned"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Every codebase has words it has decided against — a deprecated \
prefix, a vendor's reserved namespace, the `tmp`/`foo` a review keeps \
catching — and none of them are anybody else's business. Verible's \
`banned-declared-name-patterns` is the rule a project points at its \
own list, and it ships **off** with an empty list, which is exactly \
what lucisv does: with no `patterns` set the rule reports nothing and \
costs nothing.\n\n\
It judges **declared** names, not uses: every name the file's symbol \
table holds — modules, packages, types, parameters, signals, ports, \
instances, block labels, class members. A pattern must match the whole \
name, so `tmp.*` bans `tmp_addr` and `.*_tmp` bans `addr_tmp`. There \
is no fix: only the author knows what the name should have been."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "patterns",
kind: OptionKind::RegexList,
default: OptionDefault::List(&[]),
doc: "the patterns a declared name may not match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let patterns: Vec<(String, Regex)> = ctx
.option_list(NAME, "patterns")
.into_iter()
// A pattern that does not compile cannot be configured — the
// option is validated when it is read — so filtering here only
// ever drops what could not have arrived.
.filter_map(|text| Regex::compile(&text).ok().map(|regex| (text, regex)))
.collect();
if patterns.is_empty() {
return Vec::new();
}
let mut out = Vec::new();
for symbol in ctx.semantics().symbols() {
let Some((pattern, _)) =
patterns.iter().find(|(_, regex)| regex.is_match(&symbol.name))
else {
continue;
};
out.push(Violation::new(
NAME,
format!("`{}` matches the banned pattern `{pattern}`", symbol.name),
symbol.name_span,
));
}
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn banning(patterns: &str, src: &str) -> Vec<Violation> {
let mut options = RuleOptions::new();
options.set_raw(NAME, "patterns", patterns).expect("accepted");
BannedDeclaredNamePatterns.check(&LintContext::new(src, None).with_options(&options))
}
#[test]
fn nothing_is_banned_by_default() {
let src = "module m;\n logic tmp_addr;\nendmodule\n";
assert!(BannedDeclaredNamePatterns.check(&LintContext::new(src, None)).is_empty());
assert!(!BannedDeclaredNamePatterns.default_on());
}
#[test]
fn a_banned_name_is_reported_where_it_is_declared() {
let src = "module m;\n logic tmp_addr;\n logic keep_me;\nendmodule\n";
let found = banning("[\"tmp.*\"]", src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("banned pattern `tmp.*`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "tmp_addr");
assert!(found[0].fix.is_none());
}
#[test]
fn the_match_is_the_whole_name() {
let src = "module m;\n logic addr_tmp;\nendmodule\n";
assert!(banning("[\"tmp\"]", src).is_empty(), "a substring is not a match");
assert_eq!(banning("[\".*_tmp\"]", src).len(), 1);
}
#[test]
fn every_kind_of_declared_name_is_covered() {
let src = "package foo_pkg;\n typedef logic foo_t;\nendpackage\n\
module foo_mod (input logic foo_port);\n logic foo_sig;\nendmodule\n";
let found = banning("[\"foo.*\"]", src);
let names: Vec<&str> = found.iter().map(|v| &src[v.span.as_range()]).collect();
for wanted in ["foo_pkg", "foo_t", "foo_mod", "foo_port", "foo_sig"] {
assert!(names.contains(&wanted), "{wanted} missing from {names:?}");
}
}
#[test]
fn several_patterns_are_all_applied_and_findings_come_back_in_order() {
let src = "module m;\n logic tmp_a;\n logic bad_b;\nendmodule\n";
let found = banning("[\"tmp.*\", \"bad.*\"]", src);
assert_eq!(found.len(), 2);
assert!(found[0].span.start < found[1].span.start);
}
}
@@ -0,0 +1,127 @@
//! `constraint-name-style` — constraint names end in `_c`.
use crate::context::LintContext;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
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 ConstraintNameStyle;
const NAME: &str = "constraint-name-style";
impl Rule for ConstraintNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name constraints in lower_snake_case ending in _c"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A constraint block's name is what a test turns off — \
`obj.addr_range_c.constraint_mode(0)` — so it is read far from its \
declaration and needs to say what it is at the use site. Verible's \
`constraint-name-style` (enabled by default) spells the convention as \
`([a-z0-9]+_)+c`: lower-case words, then a `_c` suffix. lucisv checks \
the same pattern, on the constraints a class declares and on the \
out-of-block `constraint cls::name { … }` form.\n\n\
A prototype (`constraint c;`) is judged like a definition — it \
declares the same name. Escaped identifiers are exempt, and there is \
no fix: a rename reaches every `constraint_mode` call."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "pattern",
kind: OptionKind::Regex,
default: OptionDefault::Str("([a-z0-9]+_)+c"),
doc: "the pattern a constraint's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Constraint(decl) = &item.kind else { return };
let name = &decl.name.text;
if is_escaped(name) || fits_pattern(ctx, NAME, "pattern", name) {
return;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"pattern",
&format!("constraint `{name}`"),
"is not lower_snake_case ending in `_c`",
),
decl.name.span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
ConstraintNameStyle.check(&LintContext::new(src, None))
}
fn constraint(name: &str) -> String {
format!("class c;\n rand int addr;\n constraint {name} {{ addr > 0; }}\nendclass\n")
}
#[test]
fn flags_a_missing_suffix_and_points_at_the_name() {
let src = constraint("addr_range");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "addr_range");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
for name in ["addr_range_c", "a_c", "addr2_range_c"] {
assert!(violations(&constraint(name)).is_empty(), "{name}");
}
for name in ["c", "AddrRangeC", "addr_range", "_addr_c"] {
assert_eq!(violations(&constraint(name)).len(), 1, "{name}");
}
}
#[test]
fn a_prototype_and_an_out_of_block_definition_are_judged_too() {
let src = "class c;\n extern constraint addr_range;\nendclass\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
let src = "constraint c::addr_range { x > 0; }\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "pattern", "\"c_[a-z_0-9]+\"").expect("accepted");
let src = constraint("c_addr_range");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(ConstraintNameStyle.check(&ctx).is_empty());
let src = constraint("addr_range_c");
let ctx = LintContext::new(&src, None).with_options(&options);
assert_eq!(ConstraintNameStyle.check(&ctx).len(), 1);
}
}
@@ -2,7 +2,8 @@
//! or `_t`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::naming::{fits_pattern, is_escaped};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
@@ -36,7 +37,20 @@ impl Rule for EnumNameStyle {
same shape. Only a `typedef enum` is judged: an anonymous enum has no \
name to check, and giving it one is Verible's separate \
`typedef-enums` idea. Escaped identifiers are exempt, and there is no \
fix: a type rename reaches every use."
fix: a type rename reaches every use.\n\n\
The shape is the `style_regex` option, and its default is \
`[a-z][a-z_0-9]*(_t|_e)` — Verible's pattern with the first character \
pinned to a letter, which is what lucisv's preset checked before the \
option existed and what keeps a leading `_` reported."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str(DEFAULT_STYLE),
doc: "the pattern an enum typedef's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
@@ -47,13 +61,18 @@ impl Rule for EnumNameStyle {
return;
}
let name = &typedef.name;
let suffixed = name.ends_with("_e") || name.ends_with("_t");
if is_lower_snake_case(name) && suffixed {
if fits_pattern(ctx, NAME, "style_regex", name) {
return;
}
out.push(Violation::new(
NAME,
format!("enum `{name}` is not lower_snake_case ending in `_e` or `_t`"),
crate::naming::style_message(
ctx,
NAME,
"style_regex",
&format!("enum `{name}`"),
"is not lower_snake_case ending in `_e` or `_t`",
),
typedef.name_span,
));
});
@@ -61,6 +80,10 @@ impl Rule for EnumNameStyle {
}
}
/// Today's preset, written as a pattern: `lower_snake_case` (a letter first)
/// ending in `_e` or `_t`.
const DEFAULT_STYLE: &str = "[a-z][a-z_0-9]*(_t|_e)";
#[cfg(test)]
mod tests {
use super::*;
@@ -109,4 +132,31 @@ mod tests {
let src = typedef("state");
assert_eq!(&src[violations(&src)[0].span.as_range()], "state");
}
/// The default pattern is today's preset, character for character: a
/// leading `_` or digit is still rejected, which Verible's own
/// `[a-z_0-9]+(_t|_e)` would accept.
#[test]
fn the_default_pattern_is_the_preset_it_replaced() {
for bad in ["_state_t", "State_t", "state"] {
assert_eq!(violations(&typedef(bad)).len(), 1, "{bad}");
}
for good in ["state_t", "state_e", "s_t", "fifo2_state_e"] {
assert!(violations(&typedef(good)).is_empty(), "{good}");
}
}
#[test]
fn a_configured_pattern_replaces_it_and_is_named_in_the_message() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_e\"").expect("accepted");
let src = typedef("state_t");
let ctx = LintContext::new(&src, None).with_options(&options);
let found = EnumNameStyle.check(&ctx);
assert_eq!(found.len(), 1, "`_t` is no longer accepted");
assert!(found[0].message.contains("[a-z_0-9]+_e"), "{}", found[0].message);
let src = typedef("_state_e");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(EnumNameStyle.check(&ctx).is_empty(), "and a leading `_` now passes");
}
}
@@ -0,0 +1,330 @@
//! `explicit-begin` — a body is a `begin ... end` block, always.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{ItemKind, Stmt, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct ExplicitBegin;
const NAME: &str = "explicit-begin";
/// The eleven constructs Verible lets a project switch on one at a time, each
/// with the keyword a diagnostic names it by.
const ENABLES: [(&str, &str); 11] = [
("always_comb_enable", "always_comb"),
("always_enable", "always"),
("always_ff_enable", "always_ff"),
("always_latch_enable", "always_latch"),
("else_enable", "else"),
("final_enable", "final"),
("for_enable", "for"),
("forever_enable", "forever"),
("if_enable", "if"),
("initial_enable", "initial"),
("while_enable", "while"),
];
impl Rule for ExplicitBegin {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"wrap every body in `begin` and `end`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"The classic C bug transplanted: `if (a) x = 1;` grows a second \
statement in a later edit, the author indents it, and the compiler \
reads it as unconditional. Writing `begin ... end` from the start \
makes that edit impossible to get wrong, which is why several house \
styles require it. Verible's `explicit-begin` ships **off** — the \
style is far from universal, and a codebase that does not follow it \
would light up on the first run — and lucisv keeps it off for the same \
reason.\n\n\
Eleven `*_enable` options, exactly Verible's, switch the constructs on \
and off one at a time; all are on when the rule is. An `else if` is \
never reported: the `else`'s body is another `if`, which is the \
chained form every style guide writes. A null body (`if (a) ;`) is \
left to `suspicious-semicolon`, which has more to say about it. The \
fix wraps the body in `begin`/`end` and is **safe** — a block around \
one statement changes nothing — and running the formatter afterwards \
lays it out."
}
fn default_on(&self) -> bool {
false
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn options(&self) -> &'static [OptionSpec] {
// Written out rather than generated, because a spec table is a
// `static` and every entry needs its own `&'static str` doc.
&[
OptionSpec {
name: "always_comb_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_comb`",
},
OptionSpec {
name: "always_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always`",
},
OptionSpec {
name: "always_ff_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_ff`",
},
OptionSpec {
name: "always_latch_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_latch`",
},
OptionSpec {
name: "else_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `else`",
},
OptionSpec {
name: "final_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `final`",
},
OptionSpec {
name: "for_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `for` loop",
},
OptionSpec {
name: "forever_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `forever` loop",
},
OptionSpec {
name: "if_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `if`",
},
OptionSpec {
name: "initial_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `initial`",
},
OptionSpec {
name: "while_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `while` loop",
},
]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
let mut report = |keyword: &'static str, body: &Stmt| {
if !enabled(ctx, keyword) || is_block(body) || matches!(body.kind, StmtKind::Null) {
return;
}
out.push(
Violation::new(
NAME,
format!("`{keyword}` body is not a `begin ... end` block"),
body.span,
)
.with_fix(Fix::safe(vec![
(TextRange::new(body.span.start, body.span.start), "begin ".to_string()),
(TextRange::new(body.span.end, body.span.end), " end".to_string()),
])),
);
};
walk_items(ctx.file(), &mut |item| match &item.kind {
ItemKind::Always { kw, stmt } => {
let keyword = ENABLES
.iter()
.find_map(|(_, word)| (*word == kw).then_some(*word))
.unwrap_or("always");
if let Some(body) = procedural_body(stmt) {
report(keyword, body);
}
}
ItemKind::Initial(stmt) => {
if let Some(body) = procedural_body(stmt) {
report("initial", body);
}
}
ItemKind::Final(stmt) => {
if let Some(body) = procedural_body(stmt) {
report("final", body);
}
}
_ => {}
});
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
StmtKind::If { then, els, .. } => {
report("if", then);
// `else if` is the chained form, not a missing block.
if let Some(els) = els {
if !matches!(els.kind, StmtKind::If { .. }) {
report("else", els);
}
}
}
StmtKind::For { body, .. } => report("for", body),
StmtKind::While { body, .. } => report("while", body),
StmtKind::Forever { body } => report("forever", body),
_ => {}
});
out
}
}
/// Whether the run wants this construct checked.
fn enabled(ctx: &LintContext, keyword: &str) -> bool {
ENABLES
.iter()
.find(|(_, word)| *word == keyword)
.is_none_or(|(option, _)| ctx.option_bool(NAME, option))
}
/// The statement a procedural block really runs: the one under its timing
/// control, when it has one (`always_ff @(posedge clk) q <= d;`).
///
/// `None` for a timing control with no body at all (`always @(posedge clk);`),
/// which has nothing to wrap.
fn procedural_body(stmt: &Stmt) -> Option<&Stmt> {
match &stmt.kind {
StmtKind::Timing { stmt, .. } => stmt.as_deref(),
_ => Some(stmt),
}
}
/// Whether this statement is already a block.
fn is_block(stmt: &Stmt) -> bool {
matches!(stmt.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
ExplicitBegin.check(&LintContext::new(src, None))
}
#[test]
fn it_is_off_by_default_and_takes_veribles_eleven_options() {
assert!(!ExplicitBegin.default_on());
let names: Vec<&str> = ExplicitBegin.options().iter().map(|spec| spec.name).collect();
assert_eq!(names.len(), 11);
assert!(names.contains(&"if_enable") && names.contains(&"always_ff_enable"));
}
#[test]
fn flags_an_unblocked_if_body_and_wraps_it() {
let src = "module m;\n initial begin\n if (a) x = 1;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "x = 1;");
let fixed = apply_fixes(src, &found, false);
assert_eq!(
fixed.output,
"module m;\n initial begin\n if (a) begin x = 1; end\n end\nendmodule\n"
);
assert!(violations(&fixed.output).is_empty(), "the fix satisfies the rule");
}
#[test]
fn a_blocked_body_is_clean() {
let src = "module m;\n initial begin\n if (a) begin\n x = 1;\n end\n end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn every_construct_is_covered() {
let src = "module m;\n\
\x20 always_comb x = 1;\n\
\x20 always_ff @(posedge clk) q <= d;\n\
\x20 always @(a) y = 2;\n\
\x20 always_latch if (en) z = 3;\n\
\x20 initial x = 0;\n\
\x20 final $display(\"bye\");\n\
endmodule\n";
let found = violations(src);
// Six bodies, plus the `if` inside the always_latch.
assert_eq!(found.len(), 7, "{:#?}", found.iter().map(|v| &v.message).collect::<Vec<_>>());
let src = "module m;\n initial begin\n\
\x20 for (int i = 0; i < 2; i++) x = i;\n\
\x20 while (a) y = 1;\n\
\x20 forever z = 2;\n\
\x20 end\nendmodule\n";
assert_eq!(violations(src).len(), 3, "{:?}", violations(src));
}
#[test]
fn an_else_if_chain_is_not_a_missing_block() {
let src = "module m;\n initial begin\n if (a) begin\n x = 1;\n end\n\
\x20 else if (b) begin\n x = 2;\n end\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_bare_else_body_is_reported() {
let src =
"module m;\n initial begin\n if (a) begin\n x = 1;\n end else x = 2;\n\
\x20 end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`else`"), "{}", found[0].message);
}
#[test]
fn a_null_body_is_left_to_suspicious_semicolon() {
let src = "module m;\n initial begin\n if (a) ;\n end\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn each_option_switches_its_own_construct_off() {
let src = "module m;\n initial begin\n if (a) x = 1;\n while (b) y = 2;\n end\n\
endmodule\n";
assert_eq!(violations(src).len(), 2);
let mut options = RuleOptions::new();
options.set_raw(NAME, "if_enable", "false").expect("accepted");
let found = ExplicitBegin.check(&LintContext::new(src, None).with_options(&options));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`while`"), "{}", found[0].message);
}
#[test]
fn a_fork_join_body_is_already_a_block() {
let src = "module m;\n initial fork\n x = 1;\n join\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -0,0 +1,120 @@
//! `forbid-consecutive-null-statements` — no `;;` where a statement belongs.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::walk_all_stmts;
use vlog_parser::ast::StmtKind;
/// See [`Rule::doc`].
pub struct ForbidConsecutiveNullStatements;
const NAME: &str = "forbid-consecutive-null-statements";
impl Rule for ForbidConsecutiveNullStatements {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"remove the extra `;`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A `;` immediately after another `;` is a **null statement**: legal, \
meaningless, and almost always a typo left behind by an edit — the \
statement twin of `empty-item`. It is also a trap next to a loop or an \
`if`, where a stray `;` silently becomes the body. Verible's \
`forbid-consecutive-null-statements` (enabled by default) reports \
exactly this, and the fix deletes the extra `;`, which cannot change \
what the code means.\n\n\
The test is Verible's: a null statement whose preceding token is a \
`;`. The empty header of a `for (;;)` is not a statement and is never \
reported, and neither is the single `;` after an `end` — that one is \
the block's own terminator."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_all_stmts(ctx.file(), &mut |stmt| {
if !matches!(stmt.kind, StmtKind::Null) || !follows_a_semicolon(ctx, stmt.span.start) {
return;
}
out.push(
Violation::new(NAME, "consecutive null statement; remove the `;`", stmt.span)
.with_fix(Fix::safe(vec![(stmt.span, String::new())])),
);
});
out
}
}
/// Whether the token before `at` is a `;`.
fn follows_a_semicolon(ctx: &LintContext, at: u32) -> bool {
ctx.tokens()
.iter()
.rev()
.find(|token| token.span.end <= at)
.is_some_and(|token| token.text == ";")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
ForbidConsecutiveNullStatements.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_doubled_semicolon_and_deletes_the_extra_one() {
let src = "module m;\n initial begin\n x = 1;;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
let fixed = apply_fixes(src, &found, false);
assert_eq!(fixed.output, "module m;\n initial begin\n x = 1;\n end\nendmodule\n");
assert!(violations(&fixed.output).is_empty());
}
#[test]
fn three_in_a_row_lose_two() {
let src = "module m;\n initial begin\n x = 1;;;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 2);
assert_eq!(
apply_fixes(src, &found, false).output,
"module m;\n initial begin\n x = 1;\n end\nendmodule\n"
);
}
#[test]
fn an_empty_for_header_is_not_a_statement() {
let src = "module m;\n initial for (;;) x = 1;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_lone_null_statement_is_left_to_its_own_devices() {
// `if (x) ;` is `suspicious-semicolon`'s business, not this rule's.
let src = "module m;\n initial if (x) ;\nendmodule\n";
assert!(violations(src).is_empty());
let src = "module m;\n initial begin\n ;\n end\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_semicolon_after_an_end_is_not_one() {
let src = "module m;\n initial begin\n begin\n end;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -0,0 +1,118 @@
//! `generate-label` — every generate block carries a label.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_generate_blocks;
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct GenerateLabel;
const NAME: &str = "generate-label";
impl Rule for GenerateLabel {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"label every generate block"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"An unlabelled generate block still has a name: the tool invents one \
(`genblk3`), and that name is what appears in the hierarchy path, in \
every waveform, in every constraint file and in every error message \
the simulator prints. Renumbering happens the moment somebody adds a \
block above it, so paths written against the invented names rot \
silently. Verible's `generate-label` (enabled by default) requires the \
`begin : name`, and lucisv checks the same thing on every `if`, `for` \
and `case` generate block.\n\n\
Only a block is judged. A generate `if` whose branch is a single item \
with no `begin` opens no scope and needs no name — making it a block \
is Verible's separate `generate-begin` family, which lucisv does not \
have yet. There is no fix: only the author knows what the block should \
be called."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
if !ctx.parsed_cleanly() {
return Vec::new();
}
let mut out = Vec::new();
walk_generate_blocks(ctx.file(), &mut |block| {
if !block.is_block || block.label.is_some() {
return;
}
// Point at the `begin`, which is where the label would be written.
let begin = TextRange::new(block.span.start, block.span.start + 5);
out.push(Violation::new(NAME, "generate block has no `: label`", begin));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
GenerateLabel.check(&LintContext::new(src, None))
}
#[test]
fn flags_an_unlabelled_block_and_points_at_its_begin() {
let src = "module m;\n if (A) begin\n wire a;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "begin");
assert!(found[0].fix.is_none());
}
#[test]
fn a_labelled_block_is_clean() {
let src = "module m;\n if (A) begin : g_a\n wire a;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn every_generate_shape_is_covered() {
let src = "module m;\n\
\x20 generate\n\
\x20 for (genvar i = 0; i < 2; i++) begin\n wire a;\n end\n\
\x20 if (A) begin\n wire b;\n end else begin\n wire c;\n end\n\
\x20 case (A)\n 0: begin\n wire d;\n end\n endcase\n\
\x20 endgenerate\n\
endmodule\n";
assert_eq!(violations(src).len(), 4, "{:?}", violations(src));
}
#[test]
fn a_blockless_branch_opens_no_scope() {
let src = "module m;\n if (A) wire a;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_procedural_begin_is_not_a_generate_block() {
let src = "module m;\n initial begin\n x = 1;\n end\nendmodule\n";
assert!(violations(src).is_empty());
}
/// The opentitan false-positive class: in a file error recovery could not
/// put back together, a procedural `begin` can be rebound as a generate
/// block. The rule says nothing about such a file.
#[test]
fn a_file_that_does_not_parse_is_left_alone() {
let src = "module m;\n @@@ junk\n if (A) begin\n wire a;\n end\nendmodule\n";
let ctx = LintContext::new(src, None);
assert!(!ctx.parsed_cleanly(), "the probe needs a file that does not parse");
assert!(GenerateLabel.check(&ctx).is_empty());
}
}
@@ -0,0 +1,150 @@
//! `generate-label-prefix` — a generate block's label says it is one.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_generate_blocks;
/// See [`Rule::doc`].
pub struct GenerateLabelPrefix;
const NAME: &str = "generate-label-prefix";
impl Rule for GenerateLabelPrefix {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"prefix a generate block's label with `g_` or `gen_`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A generate label becomes a level of the instance hierarchy, so \
`top.core.fifo.data` may or may not have a generate block in the \
middle of it — and whether it does decides whether a path written in a \
testbench, an SDC file or an assertion still resolves after the code \
is re-parameterized. A prefix makes the generate levels visible in \
every such path. Verible's `generate-label-prefix` (enabled by \
default) requires one, and lucisv accepts `g_` or `gen_`, the two \
spellings real RTL uses.\n\n\
The `prefix` option is the list of accepted beginnings; an empty list \
accepts every label, which is how a project turns the shape off while \
keeping `generate-label`'s requirement that there *be* a label. There \
is no fix: renaming a block changes every hierarchical path that names \
it.\n\n\
Silent in a file that does not fully parse, for the reason \
`generate-label` gives: error recovery can rebind a procedural block \
as a generate one, and a label judged there would be judged by the \
wrong convention."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "prefix",
kind: OptionKind::List,
default: OptionDefault::List(&["g_", "gen_"]),
doc: "the beginnings a generate block's label may have",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let prefixes = ctx.option_list(NAME, "prefix");
if prefixes.is_empty() || !ctx.parsed_cleanly() {
return Vec::new();
}
let mut out = Vec::new();
walk_generate_blocks(ctx.file(), &mut |block| {
let (Some(label), Some(span)) = (&block.label, block.label_span) else { return };
if prefixes.iter().any(|prefix| label.starts_with(prefix.as_str())) {
return;
}
let wanted: Vec<String> = prefixes.iter().map(|p| format!("`{p}`")).collect();
out.push(Violation::new(
NAME,
format!("generate label `{label}` does not start with {}", wanted.join(" or ")),
span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
GenerateLabelPrefix.check(&LintContext::new(src, None))
}
fn labelled(label: &str) -> String {
format!("module m;\n if (A) begin : {label}\n wire a;\n end\nendmodule\n")
}
#[test]
fn flags_a_label_with_no_prefix_and_points_at_it() {
let src = labelled("core");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`g_` or `gen_`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "core");
assert!(found[0].fix.is_none());
}
#[test]
fn both_conventional_prefixes_are_accepted() {
assert!(violations(&labelled("g_core")).is_empty());
assert!(violations(&labelled("gen_core")).is_empty());
}
#[test]
fn an_unlabelled_block_is_generate_labels_business() {
let src = "module m;\n if (A) begin\n wire a;\n end\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_file_that_does_not_parse_is_left_alone() {
let src = "module m;\n @@@ junk\n if (A) begin : core\n wire a;\n end\nendmodule\n";
let ctx = LintContext::new(src, None);
assert!(!ctx.parsed_cleanly());
assert!(GenerateLabelPrefix.check(&ctx).is_empty());
}
#[test]
fn a_for_generate_label_is_covered() {
let src = "module m;\n for (genvar i = 0; i < 2; i++) begin : lanes\n wire a;\n end\n\
endmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_configured_list_replaces_the_default_and_an_empty_one_accepts_everything() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "prefix", "[\"blk_\"]").expect("accepted");
let src = labelled("blk_core");
assert!(GenerateLabelPrefix
.check(&LintContext::new(&src, None).with_options(&options))
.is_empty());
let src = labelled("g_core");
assert_eq!(
GenerateLabelPrefix.check(&LintContext::new(&src, None).with_options(&options)).len(),
1
);
let mut empty = RuleOptions::new();
empty.set_raw(NAME, "prefix", "[]").expect("accepted");
let src = labelled("core");
assert!(GenerateLabelPrefix
.check(&LintContext::new(&src, None).with_options(&empty))
.is_empty());
}
}
@@ -0,0 +1,138 @@
//! `interface-name-style` — interface names are `lower_snake_case` ending
//! `_if`.
use crate::context::LintContext;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
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 InterfaceNameStyle;
const NAME: &str = "interface-name-style";
impl Rule for InterfaceNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name interfaces in lower_snake_case ending in _if"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"An interface is written where a type is written — `virtual bus_if h`, \
`bus_if.master port` — and nothing in the syntax says that the \
identifier is an interface rather than a module or a class. The `_if` \
suffix is what says it, and Verible's `interface-name-style` (enabled \
by default, pattern `[a-z_0-9]+(_if)`) requires it. lucisv checks the \
same shape, on every `interface` declaration in the file.\n\n\
Only an `interface` is judged: a `module` and a `program` have their \
own conventions, and `module-name-style` is where a project that wants \
one says so. Escaped identifiers are exempt, and there is no fix — an \
interface rename reaches every port, every virtual handle and every \
file that imports it."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z_0-9]+(_if)"),
doc: "the pattern an interface's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Module(module) = &item.kind else { return };
if module.kw != "interface" || is_escaped(&module.name) {
return;
}
if fits_pattern(ctx, NAME, "style_regex", &module.name) {
return;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"style_regex",
&format!("interface `{}`", module.name),
"is not lower_snake_case ending in `_if`",
),
module.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
InterfaceNameStyle.check(&LintContext::new(src, None))
}
fn interface(name: &str) -> String {
format!("interface {name};\nendinterface\n")
}
#[test]
fn flags_a_missing_suffix_and_points_at_the_name() {
let src = interface("bus");
let found = violations(&src);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("`bus`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "bus");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
for name in ["bus_if", "clk_rst_if", "tl_if", "a_if"] {
assert!(violations(&interface(name)).is_empty(), "{name}");
}
for name in ["BusIf", "bus_IF", "bus_intf"] {
assert_eq!(violations(&interface(name)).len(), 1, "{name}");
}
}
#[test]
fn a_module_or_a_program_is_none_of_its_business() {
assert!(violations("module bus;\nendmodule\n").is_empty());
assert!(violations("program test;\nendprogram\n").is_empty());
}
#[test]
fn an_interface_inside_a_package_is_covered() {
let src = "package p;\n interface bus;\n endinterface\nendpackage\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_intf\"").expect("accepted");
let src = interface("bus_intf");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(InterfaceNameStyle.check(&ctx).is_empty());
let src = interface("bus_if");
let ctx = LintContext::new(&src, None).with_options(&options);
let found = InterfaceNameStyle.check(&ctx);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("_intf"), "{}", found[0].message);
}
}
+180
View File
@@ -0,0 +1,180 @@
//! `line-length` — no line wider than the run's width.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct LineLength;
const NAME: &str = "line-length";
impl Rule for LineLength {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"keep lines within the configured width"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A line nobody can see the end of is a line nobody reviews: side-by-side \
diffs, terminal windows and printed listings all cut at a fixed width. \
Verible's `line-length` (enabled by default, 100 columns) is this rule, \
and lucisv's default is the width **the formatter is configured with** \
for this file — `--line-length`, `lucisv.toml`, or 100 — so the two \
halves of lucisv cannot disagree about what fits. The `length` option \
overrides that for a project that lints wider than it formats.\n\n\
The check is token-aware, as Verible's is: a line that holds one \
unbreakable token — a long string literal, an `` `include`` path, a \
macro invocation — is left alone, because there is no way to wrap it \
and reporting it would only teach the user to waive the rule. A `;` or \
`,` after that token does not count as a second piece. There is no \
fix: where to break a line is what the formatter is for, and running \
it is the repair."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "length",
kind: OptionKind::Int { min: 40, max: 400 },
default: OptionDefault::Int(100),
doc: "the widest line accepted; unset means the width the formatter uses",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// The spec's default is what `--rules-doc` prints; the *run's* default
// is the formatter's width, which is why the question here is whether
// anybody set the option rather than what it reads.
let limit = if ctx.option_is_set(NAME, "length") {
ctx.option_int(NAME, "length").max(1) as usize
} else {
ctx.line_length()
};
let mut out = Vec::new();
for line in 1..=ctx.line_index().line_count() {
let Some(range) = ctx.line_index().line_range(line) else { continue };
let text = ctx.line_text(line);
let width = text.chars().count();
if width <= limit || is_unbreakable(ctx, range) {
continue;
}
// Point at the first column past the limit, as a compiler does.
let over = text.char_indices().nth(limit).map_or(text.len(), |(at, _)| at) as u32;
out.push(Violation::new(
NAME,
format!("line is {width} characters; the limit is {limit}"),
TextRange::new(range.start + over, range.end),
));
}
out
}
}
/// Whether this line is one piece of text that no wrapping could shorten.
///
/// The pieces are the tokens and the comments that touch the line, less a
/// trailing `;` or `,` — punctuation that has to sit somewhere and never
/// makes a line wrappable. One piece and it is a token: unbreakable. A
/// comment is *not* unbreakable, since prose wraps.
fn is_unbreakable(ctx: &LintContext, line: TextRange) -> bool {
let touches = |span: TextRange| span.start < line.end && line.start < span.end;
let comments = ctx.comments().into_iter().filter(|c| touches(c.span)).count();
if comments > 0 {
return false;
}
let tokens: Vec<&vlog_parser::token::Token> = ctx
.tokens()
.iter()
.filter(|token| token.kind != vlog_parser::token::TokenKind::Eof && touches(token.span))
.filter(|token| !matches!(token.text.as_str(), ";" | ","))
.collect();
tokens.len() == 1
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
LineLength.check(&LintContext::new(src, None))
}
fn line_of(width: usize) -> String {
format!("module m;\n wire {};\nendmodule\n", "a".repeat(width))
}
#[test]
fn flags_a_line_past_the_width_and_leaves_the_rest_alone() {
let src = line_of(120);
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("the limit is 100"), "{}", found[0].message);
assert!(found[0].fix.is_none(), "wrapping a line is the formatter's job");
assert!(violations(&line_of(50)).is_empty());
}
#[test]
fn it_points_at_the_first_column_past_the_limit() {
let src = line_of(120);
let found = violations(&src);
let (line, col) = LintContext::new(&src, None).line_index().line_col(found[0].span.start);
assert_eq!((line, col), (2, 101));
}
#[test]
fn the_width_is_the_one_the_formatter_was_given() {
let src = line_of(90);
assert!(violations(&src).is_empty(), "under the default 100");
let ctx = LintContext::new(&src, None).with_line_length(80);
assert_eq!(LineLength.check(&ctx).len(), 1, "and over a narrower one");
}
#[test]
fn the_option_overrides_the_formatters_width() {
let src = line_of(110);
let mut options = RuleOptions::new();
options.set_raw(NAME, "length", "120").expect("accepted");
let ctx = LintContext::new(&src, None).with_options(&options).with_line_length(80);
assert!(LineLength.check(&ctx).is_empty(), "the option beats the formatter's width");
}
#[test]
fn a_line_that_is_one_unbreakable_token_is_left_alone() {
// A long include path, a long macro invocation and a long string on a
// line of its own: none of them can be wrapped.
let long = "x".repeat(140);
for src in [
format!("`include \"{long}.svh\"\n"),
format!("module m;\n `{long}\nendmodule\n"),
format!("module m;\n initial x = 1;\nendmodule\n// {long}\n"),
] {
let found = violations(&src);
let unbreakable = !src.contains("// ");
assert_eq!(found.is_empty(), unbreakable, "{}", &src[..40.min(src.len())]);
}
}
#[test]
fn a_long_string_inside_a_statement_is_still_reported() {
// The line has other tokens, so the formatter could break it.
let src = format!("module m;\n initial $display(\"{}\");\nendmodule\n", "y".repeat(120));
assert_eq!(violations(&src).len(), 1);
}
#[test]
fn a_trailing_semicolon_does_not_make_a_line_breakable() {
let src = format!("module m;\n `{};\nendmodule\n", "z".repeat(140));
assert!(violations(&src).is_empty());
}
}
@@ -0,0 +1,173 @@
//! `macro-name-style` — `` `define`` names are `ALL_CAPS`.
use crate::context::LintContext;
use crate::naming::{fits_pattern, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
pub struct MacroNameStyle;
const NAME: &str = "macro-name-style";
impl Rule for MacroNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name macros in ALL_CAPS"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A macro is text substitution: it obeys no scope, it is invisible in a \
waveform, and it can rewrite the code around its use into something \
the reader did not write. Every language that has macros marks them by \
case for that reason, and Verible's `macro-name-style` (enabled by \
default, pattern `[A-Z_0-9]+`) is the Verilog spelling of it. lucisv \
checks the name a `` `define`` declares — not its uses, which are \
whatever the definition called itself.\n\n\
The check reads the directive text rather than a preprocessor table: \
lucisv does not expand macros, so what a file defines is exactly what \
its `` `define`` lines say. There is no fix — renaming a macro reaches \
every use, including uses in other files."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[A-Z_0-9]+"),
doc: "the pattern a macro's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
for token in ctx.tokens() {
if token.kind != TokenKind::Directive {
continue;
}
let Some((name, span)) = defined_name(&token.text, token.span.start) else { continue };
if fits_pattern(ctx, NAME, "style_regex", &name) {
continue;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"style_regex",
&format!("macro `{name}`"),
"is not ALL_CAPS",
),
span,
));
}
out
}
}
/// The name a `` `define`` directive declares, with its byte range.
///
/// `text` is the directive as the lexer kept it — from the backtick to the end
/// of the (possibly continued) line — and `at` is where it starts in the file.
fn defined_name(text: &str, at: u32) -> Option<(String, TextRange)> {
let rest = text.strip_prefix('`')?;
let rest = rest.strip_prefix("define")?;
if !rest.starts_with([' ', '\t']) {
return None;
}
let after_keyword = text.len() - rest.len();
let start = after_keyword + (rest.len() - rest.trim_start().len());
let name: String = text[start..]
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
.collect();
if name.is_empty() {
return None;
}
let start = at + start as u32;
Some((name.clone(), TextRange::new(start, start + name.len() as u32)))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
MacroNameStyle.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_lower_case_macro_and_points_at_the_name() {
let src = "`define my_macro 1\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(&src[found[0].span.as_range()], "my_macro");
assert!(found[0].fix.is_none(), "a rename reaches every use");
}
#[test]
fn all_caps_names_are_clean() {
assert!(violations("`define MY_MACRO 1\n").is_empty());
assert!(violations("`define W2 8\n").is_empty());
assert!(violations("`define MY_FN(a, b) ((a) + (b))\n").is_empty());
}
#[test]
fn a_function_like_macro_is_read_up_to_its_paren() {
let src = "`define my_fn(a) (a)\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(&src[found[0].span.as_range()], "my_fn");
}
#[test]
fn other_directives_and_uses_are_none_of_its_business() {
for src in [
"`include \"lower_case.svh\"\n",
"`ifdef lower_case\n`endif\n",
"`timescale 1ns / 1ps\n",
"module m;\n `my_macro\nendmodule\n",
"`undef my_macro\n",
] {
assert!(violations(src).is_empty(), "{src}");
}
}
#[test]
fn a_definition_inside_a_module_is_found_too() {
let src = "module m;\n`define inner 1\nendmodule\n";
assert_eq!(violations(src).len(), 1);
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+\"").expect("accepted");
let ctx = LintContext::new("`define my_macro 1\n", None).with_options(&options);
assert!(MacroNameStyle.check(&ctx).is_empty());
let ctx = LintContext::new("`define MY_MACRO 1\n", None).with_options(&options);
let found = MacroNameStyle.check(&ctx);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("[a-z_0-9]+"), "{}", found[0].message);
}
#[test]
fn a_multi_line_definition_is_read_from_its_first_line() {
let src = "`define my_macro(a) \\\n do_something(a)\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(&src[found[0].span.as_range()], "my_macro");
}
}
+18
View File
@@ -7,19 +7,29 @@
//! `instance-shadowing` through `vlog_semantic::Semantics` directly (see
//! `docs/features/linter-expansion-1/README.md`).
pub mod always_comb;
pub mod always_comb_blocking;
pub mod always_ff_non_blocking;
pub mod banned_declared_name_patterns;
pub mod case_missing_default;
pub mod constraint_name_style;
pub mod duplicate_declaration;
pub mod empty_item;
pub mod enum_name_style;
pub mod explicit_begin;
pub mod explicit_function_task_parameter_type;
pub mod explicit_parameter_storage_type;
pub mod forbid_consecutive_null_statements;
pub mod forbid_defparam;
pub mod forbid_negative_array_dim;
pub mod generate_label;
pub mod generate_label_prefix;
pub mod incomplete_assignment;
pub mod instance_shadowing;
pub mod interface_name_style;
pub mod invalid_system_task_function;
pub mod line_length;
pub mod macro_name_style;
pub mod mismatched_labels;
pub mod module_filename;
pub mod module_name_style;
@@ -28,12 +38,20 @@ pub mod module_port;
pub mod multiply_driven;
pub mod no_tabs;
pub mod no_trailing_whitespace;
pub mod one_module_per_file;
pub mod package_filename;
pub mod packed_dimensions_range_ordering;
pub mod parameter_name_style;
pub mod parameter_type_name_style;
pub mod plusarg_assignment;
pub mod port_name_suffix;
pub mod posix_eof;
pub mod signal_name_style;
pub mod struct_union_name_style;
pub mod suspicious_semicolon;
pub mod truncated_numeric_literal;
pub mod typedef_enums;
pub mod typedef_structs_unions;
pub mod undeclared_identifier;
pub mod undersized_binary_literal;
pub mod undriven_net;
@@ -1,7 +1,8 @@
//! `module-name-style` — module names are `lower_snake_case`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
@@ -36,23 +37,44 @@ impl Rule for ModuleNameStyle {
here, Verible ships no `module-name-style` rule to inherit a default \
from, so enabling it is the user's call — `--select \
module-name-style`. Escaped identifiers (`\\my$mod`) are exempt, and \
there is no fix: renaming a module is a cross-file edit."
there is no fix: renaming a module is a cross-file edit.\n\n\
The shape is the `style_regex` option, default `[a-z][a-z_0-9]*` — \
the preset this rule checked before the option existed. The rule \
judges every `module`, `interface` and `program` name; a project that \
wants the `_if` convention for its interfaces has \
`interface-name-style` for that, and turning both on holds an \
interface to both."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z][a-z_0-9]*"),
doc: "the pattern a module's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Module(module) = &item.kind else { return };
if is_escaped(&module.name) || is_lower_snake_case(&module.name) {
if is_escaped(&module.name) || fits_pattern(ctx, NAME, "style_regex", &module.name) {
return;
}
out.push(Violation::new(
NAME,
format!("module `{}` is not lower_snake_case", module.name),
style_message(
ctx,
NAME,
"style_regex",
&format!("module `{}`", module.name),
"is not lower_snake_case",
),
module.name_span,
));
});
@@ -99,4 +121,26 @@ mod tests {
fn it_is_off_by_default() {
assert!(!ModuleNameStyle.default_on());
}
#[test]
fn the_default_pattern_is_the_preset_it_replaced() {
for bad in ["_foo", "FooBar", "fooBar"] {
assert_eq!(violations(&format!("module {bad};\nendmodule\n")).len(), 1, "{bad}");
}
for good in ["foo", "foo_bar", "fifo2_ctrl"] {
assert!(violations(&format!("module {good};\nendmodule\n")).is_empty(), "{good}");
}
}
#[test]
fn a_configured_pattern_replaces_it() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[A-Z][A-Za-z0-9]*\"").expect("accepted");
let ctx = LintContext::new("module FooBar;\nendmodule\n", None).with_options(&options);
assert!(ModuleNameStyle.check(&ctx).is_empty());
let ctx = LintContext::new("module foo_bar;\nendmodule\n", None).with_options(&options);
let found = ModuleNameStyle.check(&ctx);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("[A-Z][A-Za-z0-9]*"), "{}", found[0].message);
}
}
@@ -0,0 +1,134 @@
//! `one-module-per-file` — one module declaration per file.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct OneModulePerFile;
const NAME: &str = "one-module-per-file";
impl Rule for OneModulePerFile {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare one module per file"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Every tool that finds a module by searching a library directory looks \
for one named `<module>.sv`, and `module-filename` ties the file to the \
module it declares — a claim that only means something when there is \
exactly one. Verible's `one-module-per-file` is **off** by default and \
so is this one: plenty of real RTL keeps a handful of small helper \
modules beside the one the file is named for, and that is a project's \
choice rather than a mistake.\n\n\
Only the file's own `module` declarations count. An `interface`, a \
`program` and a `package` are not modules — a package of types beside \
the module that uses them is the common shape this rule must not \
punish.\n\n\
Silent in a file that does not fully parse: error recovery unwinds to \
file scope, so a `module` written inside something the parser could \
not finish reappears as a second top-level declaration — an accusation \
about text the author never wrote that way."
}
fn default_on(&self) -> bool {
false
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
if !ctx.parsed_cleanly() {
return Vec::new();
}
let modules: Vec<_> = ctx
.file()
.items
.iter()
.filter_map(|item| match &item.kind {
ItemKind::Module(module) if module.kw == "module" => Some(module),
_ => None,
})
.collect();
let Some(first) = modules.first() else { return Vec::new() };
modules
.iter()
.skip(1)
.map(|module| {
Violation::new(
NAME,
format!(
"module `{}` is the file's second declaration; `{}` is the first",
module.name, first.name
),
module.name_span,
)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
OneModulePerFile.check(&LintContext::new(src, None))
}
#[test]
fn flags_every_module_after_the_first() {
let src = "module a;\nendmodule\nmodule b;\nendmodule\nmodule c;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 2);
assert!(found[0].message.contains("`b`"), "{}", found[0].message);
assert!(found[0].message.contains("`a` is the first"), "{}", found[0].message);
assert_eq!(&src[found[1].span.as_range()], "c");
}
#[test]
fn one_module_is_clean() {
assert!(violations("module a;\nendmodule\n").is_empty());
assert!(violations("package p;\nendpackage\n").is_empty());
}
#[test]
fn a_package_or_an_interface_beside_a_module_is_not_a_second_module() {
let src = "package p;\nendpackage\nmodule a;\nendmodule\ninterface i;\nendinterface\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
/// The everyday shape this rule must not punish: one module, and the
/// package of types it uses, in the same file.
#[test]
fn a_package_and_a_program_beside_one_module_are_clean() {
let src = "package p;\n typedef logic w_t;\nendpackage\n\
module a;\nendmodule\n\
program t;\nendprogram\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_file_that_does_not_parse_is_left_alone() {
// Recovery can promote a module the author nested inside something
// else to file scope; this rule must not accuse them of it.
let src = "module a;\n module inner;\n endmodule\nendmodule\n";
let ctx = LintContext::new(src, None);
assert!(!ctx.parsed_cleanly(), "a nested module does not parse");
assert!(OneModulePerFile.check(&ctx).is_empty());
}
#[test]
fn it_is_off_by_default() {
assert!(!OneModulePerFile.default_on());
}
}
@@ -0,0 +1,144 @@
//! `package-filename` — a one-package file is named after its package.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::ItemKind;
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct PackageFilename;
const NAME: &str = "package-filename";
impl Rule for PackageFilename {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name a one-package file after its package"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A package is imported by name and found by file name, so the two \
disagreeing costs the same grep every time. Verible's \
`package-filename` (enabled by default) requires the file to be named \
after the package it declares, and accepts a `_pkg` suffix on the file \
that the package name does not carry — `foo` in `foo_pkg.sv` is the \
convention half of the industry writes. lucisv accepts both spellings \
for the same reason.\n\n\
Like `module-filename`, it speaks only when the file declares exactly \
one package, is silent for input with no file name (stdin), and offers \
no fix: renaming a file is not the linter's business. The \
`allow-dash-for-underscore` option lets a file named `foo-pkg.sv` \
satisfy a package called `foo_pkg`, which is Verible's option of the \
same name on `module-filename`. It is also silent in a file that does \
not fully parse: `exactly one package` is a claim about structure, and \
error recovery can invent a second one."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "allow-dash-for-underscore",
kind: OptionKind::Bool,
default: OptionDefault::Bool(false),
doc: "treat a `-` in the file name as the `_` of the package name",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
if !ctx.parsed_cleanly() {
return Vec::new();
}
let Some(path) = ctx.path() else { return Vec::new() };
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { return Vec::new() };
let mut packages = ctx.file().items.iter().filter_map(|item| match &item.kind {
ItemKind::Package { name, name_span, .. } => Some((name, *name_span)),
_ => None,
});
let (Some((name, span)), None) = (packages.next(), packages.next()) else {
return Vec::new();
};
let stem = if ctx.option_bool(NAME, "allow-dash-for-underscore") {
stem.replace('-', "_")
} else {
stem.to_string()
};
if stem == *name || stem == format!("{name}_pkg") {
return Vec::new();
}
let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or(&stem);
vec![report(name, span, file_name)]
}
}
fn report(name: &str, span: TextRange, file_name: &str) -> Violation {
Violation::new(NAME, format!("package `{name}` does not match file name `{file_name}`"), span)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
use std::path::PathBuf;
fn violations(src: &str, path: Option<&str>) -> Vec<Violation> {
PackageFilename.check(&LintContext::new(src, path.map(PathBuf::from)))
}
fn package(name: &str) -> String {
format!("package {name};\nendpackage\n")
}
#[test]
fn flags_a_mismatch_and_points_at_the_name() {
let src = package("foo_pkg");
let found = violations(&src, Some("rtl/bar.sv"));
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("bar.sv"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "foo_pkg");
assert!(found[0].fix.is_none());
}
#[test]
fn both_conventional_spellings_are_accepted() {
assert!(violations(&package("foo_pkg"), Some("rtl/foo_pkg.sv")).is_empty());
assert!(violations(&package("foo"), Some("rtl/foo.sv")).is_empty());
assert!(violations(&package("foo"), Some("rtl/foo_pkg.sv")).is_empty(), "the `_pkg` file");
assert!(violations(&package("foo"), Some("rtl/foo.svh")).is_empty());
}
#[test]
fn silent_without_a_file_name_or_with_more_than_one_package() {
assert!(violations(&package("foo"), None).is_empty());
let two = "package a;\nendpackage\npackage b;\nendpackage\n";
assert!(violations(two, Some("rtl/c.sv")).is_empty());
assert!(violations("module m;\nendmodule\n", Some("rtl/c.sv")).is_empty());
}
#[test]
fn a_file_that_does_not_parse_is_left_alone() {
let src = "package foo_pkg;\n @@@ junk\nendpackage\n";
let ctx = LintContext::new(src, Some(PathBuf::from("rtl/bar.sv")));
assert!(!ctx.parsed_cleanly());
assert!(PackageFilename.check(&ctx).is_empty());
}
#[test]
fn a_dash_stands_for_an_underscore_only_when_asked() {
let src = package("foo_pkg");
assert_eq!(violations(&src, Some("rtl/foo-pkg.sv")).len(), 1);
let mut options = RuleOptions::new();
options.set_raw(NAME, "allow-dash-for-underscore", "true").expect("accepted");
let ctx =
LintContext::new(&src, Some(PathBuf::from("rtl/foo-pkg.sv"))).with_options(&options);
assert!(PackageFilename.check(&ctx).is_empty());
}
}
@@ -1,7 +1,8 @@
//! `parameter-name-style` — parameter names are `CamelCase` or `ALL_CAPS`.
use crate::context::LintContext;
use crate::naming::{is_camel_case, is_escaped, is_upper_snake_case};
use crate::naming::{fits_style, is_escaped, STYLE_WORDS};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
@@ -34,23 +35,57 @@ impl Rule for ParameterNameStyle {
this, with `CamelCase` and `ALL_CAPS` as its presets. lucisv accepts \
either preset for both `parameter` and `localparam` — Verible's \
default is stricter for `localparam` (`CamelCase` only), which would \
flag most `localparam int FOO_BAR` in existing RTL; until per-rule \
style configuration exists, the union is the honest default. The rule \
covers item- and statement-level declarations and the `#( ... )` \
parameter ports of module and class headers. Escaped identifiers are \
exempt, and there is no fix: a rename reaches every override site."
flag most `localparam int FOO_BAR` in existing RTL, so the union is \
the default here and the option is where a project says otherwise. \
The rule covers item- and statement-level declarations and the \
`#( ... )` parameter ports of module and class headers. Escaped \
identifiers are exempt, and there is no fix: a rename reaches every \
override site.\n\n\
Four options, spelled as Verible spells them: `parameter_style` and \
`localparam_style` take `CamelCase`, `ALL_CAPS`, or both joined with \
`|`; `parameter_style_regex` and `localparam_style_regex` replace the \
words with a pattern for a project whose convention is neither."
}
fn options(&self) -> &'static [OptionSpec] {
&[
OptionSpec {
name: "localparam_style",
kind: OptionKind::Words(&STYLE_WORDS),
default: OptionDefault::Str(BOTH_PRESETS),
doc: "the presets a `localparam` name may take, joined with `|`",
},
OptionSpec {
name: "localparam_style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str(""),
doc: "a pattern a `localparam` name must match instead of the presets",
},
OptionSpec {
name: "parameter_style",
kind: OptionKind::Words(&STYLE_WORDS),
default: OptionDefault::Str(BOTH_PRESETS),
doc: "the presets a `parameter` name may take, joined with `|`",
},
OptionSpec {
name: "parameter_style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str(""),
doc: "a pattern a `parameter` name must match instead of the presets",
},
]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
if let ItemKind::ParamDecl(decl) = &item.kind {
check_decl(decl, &mut out);
check_decl(ctx, decl, &mut out);
}
});
walk_all_stmts(ctx.file(), &mut |stmt| {
if let StmtKind::ParamDecl(decl) = &stmt.kind {
check_decl(decl, &mut out);
check_decl(ctx, decl, &mut out);
}
});
walk_param_ports(ctx.file(), &mut |port| {
@@ -62,29 +97,41 @@ impl Rule for ParameterNameStyle {
return;
}
let kw = port.kw.as_deref().unwrap_or("parameter");
report(&port.name, port.name_span, kw, &mut out);
report(ctx, &port.name, port.name_span, kw, &mut out);
});
out
}
}
/// The presets both keywords accept unless a project says otherwise.
const BOTH_PRESETS: &str = "CamelCase|ALL_CAPS";
/// Reports every declarator of one `parameter`/`localparam` declaration.
fn check_decl(decl: &ParamDecl, out: &mut Vec<Violation>) {
fn check_decl(ctx: &LintContext, decl: &ParamDecl, out: &mut Vec<Violation>) {
for declarator in &decl.declarators {
report(&declarator.name, declarator.name_span, &decl.kw, out);
report(ctx, &declarator.name, declarator.name_span, &decl.kw, out);
}
}
/// Reports `name` unless it matches one of the two accepted presets.
fn report(name: &str, span: TextRange, kw: &str, out: &mut Vec<Violation>) {
if is_escaped(name) || is_camel_case(name) || is_upper_snake_case(name) {
/// Reports `name` unless it fits the style the run asks of its keyword.
fn report(ctx: &LintContext, name: &str, span: TextRange, kw: &str, out: &mut Vec<Violation>) {
let (style, regex) = if kw == "localparam" {
("localparam_style", "localparam_style_regex")
} else {
("parameter_style", "parameter_style_regex")
};
if is_escaped(name) || fits_style(ctx, NAME, style, regex, name) {
return;
}
out.push(Violation::new(
NAME,
format!("`{kw}` `{name}` is neither CamelCase nor ALL_CAPS"),
span,
));
let subject = format!("`{kw}` `{name}`");
let message = if ctx.option_is_set(NAME, regex) {
format!("{subject} does not match `{}`", ctx.option_str(NAME, regex))
} else if ctx.option_is_set(NAME, style) {
format!("{subject} is not {}", ctx.option_str(NAME, style).replace('|', " or "))
} else {
format!("{subject} is neither CamelCase nor ALL_CAPS")
};
out.push(Violation::new(NAME, message, span));
}
#[cfg(test)]
@@ -141,4 +188,36 @@ mod tests {
fn it_is_on_by_default() {
assert!(ParameterNameStyle.default_on());
}
fn with(options: &crate::options::RuleOptions, src: &str) -> Vec<Violation> {
ParameterNameStyle.check(&LintContext::new(src, None).with_options(options))
}
/// Verible's own default — `localparam_style: CamelCase` — is one option
/// away, and it separates the two keywords as Verible does.
#[test]
fn the_two_keywords_take_their_own_styles() {
let src = "module m;\n parameter int ADDR_W = 8;\n localparam int MAX_DEPTH = 4;\n\
endmodule\n";
assert!(violations(src).is_empty(), "both presets by default");
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "localparam_style", "\"CamelCase\"").expect("accepted");
let found = with(&options, src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("MAX_DEPTH"), "{}", found[0].message);
assert!(found[0].message.contains("is not CamelCase"), "{}", found[0].message);
}
#[test]
fn a_pattern_replaces_the_presets_for_that_keyword_only() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "parameter_style_regex", "\"p_[a-z_0-9]+\"").expect("accepted");
let src = "module m;\n parameter int p_width = 8;\n localparam int MAX_DEPTH = 4;\n\
endmodule\n";
assert!(with(&options, src).is_empty(), "the localparam keeps its presets");
let src = "module m;\n parameter int Width = 8;\nendmodule\n";
let found = with(&options, src);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("p_[a-z_0-9]+"), "{}", found[0].message);
}
}
@@ -0,0 +1,124 @@
//! `parameter-type-name-style` — `type` parameters are named like types.
use crate::context::LintContext;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_param_ports;
/// See [`Rule::doc`].
pub struct ParameterTypeNameStyle;
const NAME: &str = "parameter-type-name-style";
impl Rule for ParameterTypeNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name type parameters in lower_snake_case ending in _t"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A `type` parameter is a type, not a constant: it is written where \
`logic` or `addr_t` is written, and naming it `T` or `WIDTH_T` makes \
a declaration read like an expression. Verible's \
`parameter-type-name-style` asks for the same `lower_snake_case` with \
a `_t` suffix every other type name here carries, and ships it **off**; \
lucisv keeps it off, because the single-letter `#(type T = int)` is \
near-universal in UVM code and switching this on for such a codebase \
would report every class in it.\n\n\
Only a `type` parameter is judged — an ordinary one is \
`parameter-name-style`'s. Escaped identifiers are exempt, and there is \
no fix: a rename reaches every override site."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z][a-z_0-9]*_t"),
doc: "the pattern a type parameter's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_param_ports(ctx.file(), &mut |port| {
if !port.is_type || is_escaped(&port.name) {
return;
}
if fits_pattern(ctx, NAME, "style_regex", &port.name) {
return;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"style_regex",
&format!("type parameter `{}`", port.name),
"is not lower_snake_case ending in `_t`",
),
port.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
ParameterTypeNameStyle.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_single_letter_type_parameter() {
let src = "class c #(type T = int);\nendclass\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "T");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
assert!(violations("class c #(type item_t = int);\nendclass\n").is_empty());
assert!(violations("module m #(type addr_t = logic) ();\nendmodule\n").is_empty());
}
#[test]
fn an_ordinary_parameter_is_none_of_its_business() {
assert!(violations("module m #(parameter int Width = 8) ();\nendmodule\n").is_empty());
assert!(violations("module m;\n parameter int width = 8;\nendmodule\n").is_empty());
}
#[test]
fn it_is_off_by_default() {
assert!(!ParameterTypeNameStyle.default_on());
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[A-Z]\"").expect("accepted");
let ctx =
LintContext::new("class c #(type T = int);\nendclass\n", None).with_options(&options);
assert!(ParameterTypeNameStyle.check(&ctx).is_empty());
}
}
@@ -0,0 +1,193 @@
//! `port-name-suffix` — a port's name says which way it points.
use crate::context::LintContext;
use crate::module_decls::module_signals;
use crate::naming::is_escaped;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
/// See [`Rule::doc`].
pub struct PortNameSuffix;
const NAME: &str = "port-name-suffix";
/// The six suffixes Verible knows, and the direction each one claims.
const KNOWN: [(&str, &str); 6] = [
("_i", "input"),
("_ni", "input"),
("_o", "output"),
("_no", "output"),
("_io", "inout"),
("_nio", "inout"),
];
impl Rule for PortNameSuffix {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"end a port's name with the suffix for its direction"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"At an instantiation, `.data(data)` says nothing about which way the \
signal flows; `.data_i(data_o)` says it at a glance, and a mistake in \
a connection list becomes visible without opening the module. The \
lowRISC style guide asks for it and Verible's `port-name-suffix` \
checks it: `_i` / `_ni` for an input, `_o` / `_no` for an output, \
`_io` / `_nio` for an `inout`, where the `n` marks an active-low \
signal. Both ship it **off** — a codebase that did not start with the \
convention cannot adopt it one port at a time — and lucisv does too.\n\n\
The `suffixes` option is the list of accepted endings. A suffix in it \
that is one of the six known ones is accepted **only for its own \
direction**, so shortening the list to `[\"_i\", \"_o\"]` bans the \
active-low spellings without letting an input end in `_o`; any other \
suffix a project adds is accepted for every direction, since only the \
project knows what it means. A port whose direction the header does \
not state — a non-ANSI name, declared in the body — is judged where \
the body declares it. Escaped identifiers are exempt, and there is no \
fix: renaming a port reaches every instantiation."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "suffixes",
kind: OptionKind::List,
default: OptionDefault::List(&["_i", "_ni", "_o", "_no", "_io", "_nio"]),
doc: "the endings a port name may have",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let configured = ctx.option_list(NAME, "suffixes");
let mut out = Vec::new();
for port in module_signals(ctx.file()) {
let (Some(dir), "port") = (port.dir.as_deref(), port.what) else { continue };
if is_escaped(&port.name) {
continue;
}
let allowed = allowed_for(&configured, dir);
if allowed.is_empty() || allowed.iter().any(|s| port.name.ends_with(s.as_str())) {
continue;
}
out.push(Violation::new(
NAME,
format!("{dir} port `{}` does not end in {}", port.name, or_list(&allowed)),
port.span,
));
}
out
}
}
/// The configured suffixes this direction may use: a known suffix only where
/// it belongs, and anything the project added everywhere.
fn allowed_for(configured: &[String], dir: &str) -> Vec<String> {
configured
.iter()
.filter(|suffix| {
KNOWN.iter().find(|(known, _)| known == suffix).is_none_or(|(_, wants)| *wants == dir)
})
.cloned()
.collect()
}
/// "`_i` or `_ni`" — the list as a sentence.
fn or_list(suffixes: &[String]) -> String {
let quoted: Vec<String> = suffixes.iter().map(|s| format!("`{s}`")).collect();
match quoted.split_last() {
Some((last, [])) => last.clone(),
Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
None => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
PortNameSuffix.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_port_with_no_suffix_and_names_what_it_wanted() {
let src = "module m (input logic clk, output logic data);\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 2, "{found:?}");
assert!(found[0].message.contains("input port `clk`"), "{}", found[0].message);
assert!(found[0].message.contains("`_i` or `_ni`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "clk");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
let src = "module m (input logic clk_i, input logic rst_ni, output logic data_o,\n\
\x20 output logic ack_no, inout wire sda_io, inout wire scl_nio);\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_suffix_for_the_wrong_direction_is_still_wrong() {
let src = "module m (input logic data_o);\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("input port `data_o`"), "{}", found[0].message);
}
#[test]
fn a_body_declared_port_is_judged_where_its_direction_is() {
// The non-ANSI header only lists the name; the body declaration is
// the one that carries the direction, and the one reported.
let src = "module m (clk);\n input clk;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].span.start as usize, src.rfind("clk").unwrap_or(0));
}
#[test]
fn a_signal_is_not_a_port() {
assert!(violations("module m;\n logic internal;\nendmodule\n").is_empty());
}
#[test]
fn shortening_the_list_bans_the_active_low_spellings() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "suffixes", "[\"_i\", \"_o\"]").expect("accepted");
let src = "module m (input logic rst_ni, input logic clk_i, output logic data_o);\n\
endmodule\n";
let ctx = LintContext::new(src, None).with_options(&options);
let found = PortNameSuffix.check(&ctx);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("rst_ni"), "{}", found[0].message);
assert!(found[0].message.contains("does not end in `_i`"), "{}", found[0].message);
}
#[test]
fn a_project_specific_suffix_is_accepted_in_every_direction() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "suffixes", "[\"_pin\"]").expect("accepted");
let src = "module m (input logic clk_pin, output logic data_pin);\nendmodule\n";
let ctx = LintContext::new(src, None).with_options(&options);
assert!(PortNameSuffix.check(&ctx).is_empty());
}
#[test]
fn it_is_off_by_default() {
assert!(!PortNameSuffix.default_on());
}
}
+100
View File
@@ -0,0 +1,100 @@
//! `posix-eof` — a file ends with a newline.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct PosixEof;
const NAME: &str = "posix-eof";
impl Rule for PosixEof {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"end the file with a newline"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"POSIX defines a line as ending in a newline, so a file whose last line \
has none has, formally, no last line: `cat` runs the next file into it, \
`wc -l` counts one line short, and every diff of a later edit shows the \
final line twice — once removed, once added with the newline. Verible's \
`posix-eof` (enabled by default) asks for the newline and so does \
lucisv's formatter, which always writes one. The fix appends it, which \
cannot change what the code means. An empty file has no last line to \
terminate and is left alone."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let source = ctx.source();
if source.is_empty() || source.ends_with('\n') {
return Vec::new();
}
let end = source.len() as u32;
// The diagnostic points at the last character, which is where an
// editor's cursor lands; the fix appends past it.
let last = source.chars().next_back().map_or(end, |c| end - c.len_utf8() as u32);
vec![Violation::new(NAME, "file does not end with a newline", TextRange::new(last, end))
.with_fix(Fix::safe(vec![(TextRange::new(end, end), "\n".to_string())]))]
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
PosixEof.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_missing_newline_and_appends_one() {
let src = "module m;\nendmodule";
let found = violations(src);
assert_eq!(found.len(), 1);
let fixed = apply_fixes(src, &found, false);
assert_eq!(fixed.output, "module m;\nendmodule\n");
assert!(violations(&fixed.output).is_empty());
}
#[test]
fn a_terminated_file_is_clean() {
assert!(violations("module m;\nendmodule\n").is_empty());
assert!(violations("\n").is_empty());
}
#[test]
fn an_empty_file_has_no_last_line() {
assert!(violations("").is_empty());
}
#[test]
fn it_points_at_the_last_character() {
let src = "module m;\nendmodule";
let found = violations(src);
assert_eq!(&src[found[0].span.as_range()], "e");
}
#[test]
fn a_multibyte_last_character_is_not_split() {
let src = "// naïve";
let found = violations(src);
assert_eq!(&src[found[0].span.as_range()], "e");
assert_eq!(apply_fixes(src, &found, false).output, "// naïve\n");
}
}
@@ -0,0 +1,151 @@
//! `signal-name-style` — nets, variables and ports are `lower_snake_case`.
use crate::context::LintContext;
use crate::module_decls::module_signals;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
/// See [`Rule::doc`].
pub struct SignalNameStyle;
const NAME: &str = "signal-name-style";
impl Rule for SignalNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name signals in lower_snake_case"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A signal name is read in a waveform viewer next to a hundred others, \
and a codebase that mixes `dataValid`, `DATA_VALID` and `data_valid` \
makes every one of those a separate grep. Verible's \
`signal-name-style` spells the convention as `[a-z_0-9]+` and ships it \
**off**; lucisv keeps it off for the same reason \
`parameter-name-style` keeps its union of presets — a naming rule \
switched on for an existing codebase reports thousands of findings on \
its first run, and that is a project's decision to make.\n\n\
It judges the nets, variables and ports declared **inside a module, \
interface or program**: the ANSI ports of the header, the non-ANSI \
`input`/`output` declarations of the body, and the `wire`/`logic`/`reg` \
declarations beside them. A class property is not a signal and is left \
alone; a `parameter` is `parameter-name-style`'s, and a `genvar` names \
a loop, not a wire. Escaped identifiers are exempt, and there is no \
fix: renaming a signal reaches every use, including uses in other \
files."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z_0-9]+"),
doc: "the pattern a signal's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
for signal in module_signals(ctx.file()) {
if is_escaped(&signal.name) || fits_pattern(ctx, NAME, "style_regex", &signal.name) {
continue;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"style_regex",
&format!("{} `{}`", signal.what, signal.name),
"is not lower_snake_case",
),
signal.span,
));
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
SignalNameStyle.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_camel_case_signal_and_names_what_it_is() {
let src = "module m;\n logic dataValid;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.starts_with("signal `dataValid`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "dataValid");
assert!(found[0].fix.is_none());
}
#[test]
fn ports_of_both_header_styles_are_covered() {
let ansi = "module m (input logic clkIn, output wire dataOut);\nendmodule\n";
assert_eq!(violations(ansi).len(), 2, "{:?}", violations(ansi));
assert!(violations(ansi)[0].message.starts_with("port `clkIn`"));
let non_ansi = "module m (clkIn, dataOut);\n input clkIn;\n output dataOut;\nendmodule\n";
// Once each: the header lists the names, the body declares them, and
// the declaration is what is reported.
assert_eq!(violations(non_ansi).len(), 2, "{:?}", violations(non_ansi));
assert!(violations(non_ansi)[0].span.start as usize > non_ansi.find(");").unwrap_or(0));
}
#[test]
fn conventional_names_are_clean() {
let src = "module m (input logic clk_i, output wire data_o);\n logic [7:0] wr_ptr2;\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_signal_inside_a_generate_block_is_covered() {
let src = "module m;\n generate\n if (A) begin : g\n logic dataValid;\n\
\x20 end\n endgenerate\nendmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_class_property_and_a_parameter_are_not_signals() {
assert!(violations("class c;\n logic dataValid;\nendclass\n").is_empty());
assert!(violations("module m;\n parameter int AddrWidth = 1;\nendmodule\n").is_empty());
assert!(violations("module m;\n genvar iGen;\nendmodule\n").is_empty());
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z][a-zA-Z0-9]*\"").expect("accepted");
let ctx = LintContext::new("module m;\n logic dataValid;\nendmodule\n", None)
.with_options(&options);
assert!(SignalNameStyle.check(&ctx).is_empty());
let ctx = LintContext::new("module m;\n logic data_valid;\nendmodule\n", None)
.with_options(&options);
assert_eq!(SignalNameStyle.check(&ctx).len(), 1);
}
#[test]
fn it_is_off_by_default() {
assert!(!SignalNameStyle.default_on());
}
}
@@ -2,7 +2,8 @@
//! `lower_snake_case` ending `_t`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
@@ -36,7 +37,20 @@ impl Rule for StructUnionNameStyle {
a `typedef struct` / `typedef union` is judged — an anonymous struct \
has no name, and requiring it to have one is Verible's separate \
`typedef-structs-unions` idea. Escaped identifiers are exempt, and \
there is no fix: a type rename reaches every use."
there is no fix: a type rename reaches every use.\n\n\
The shape is the `style_regex` option, whose default \
`[a-z][a-z_0-9]*_t` is Verible's pattern with the first character \
pinned to a letter — the preset lucisv checked before the option \
existed."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z][a-z_0-9]*_t"),
doc: "the pattern a struct or union typedef's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
@@ -45,12 +59,18 @@ impl Rule for StructUnionNameStyle {
let ItemKind::Typedef(typedef) = &item.kind else { return };
let TypedefKind::Struct(structure) = &typedef.kind else { return };
let name = &typedef.name;
if is_escaped(name) || (is_lower_snake_case(name) && name.ends_with("_t")) {
if is_escaped(name) || fits_pattern(ctx, NAME, "style_regex", name) {
return;
}
out.push(Violation::new(
NAME,
format!("{} `{name}` is not lower_snake_case ending in `_t`", structure.kw),
style_message(
ctx,
NAME,
"style_regex",
&format!("{} `{name}`", structure.kw),
"is not lower_snake_case ending in `_t`",
),
typedef.name_span,
));
});
@@ -101,6 +121,30 @@ mod tests {
assert!(violations(src).is_empty());
}
#[test]
fn the_default_pattern_is_the_preset_it_replaced() {
for bad in ["_addr_t", "AddrT", "addr"] {
assert_eq!(violations(&typedef("struct", bad)).len(), 1, "{bad}");
}
for good in ["addr_t", "a_t", "word2_t"] {
assert!(violations(&typedef("struct", good)).is_empty(), "{good}");
}
}
#[test]
fn a_configured_pattern_replaces_it() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_s\"").expect("accepted");
let src = typedef("struct", "addr_s");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(StructUnionNameStyle.check(&ctx).is_empty());
let src = typedef("struct", "addr_t");
let ctx = LintContext::new(&src, None).with_options(&options);
let found = StructUnionNameStyle.check(&ctx);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("[a-z_0-9]+_s"), "{}", found[0].message);
}
#[test]
fn a_struct_typedef_inside_a_class_body_is_covered() {
let src = "class c;\n typedef struct packed { logic a; } addr;\nendclass\n";
@@ -0,0 +1,106 @@
//! `typedef-enums` — an `enum` type is declared with a `typedef`.
use crate::context::LintContext;
use crate::decls::walk_declared_types;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::TypeExtra;
/// See [`Rule::doc`].
pub struct TypedefEnums;
const NAME: &str = "typedef-enums";
impl Rule for TypedefEnums {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"give an enum type a name with `typedef`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"An anonymous `enum logic [1:0] {IDLE, BUSY} state;` gives the enum no \
name, and the language gives no way to write one afterwards: a \
function cannot take the type, a port cannot carry it, a cast cannot \
name it, and a second variable of the same states has to repeat the \
whole list — where the two copies are *different* types to the \
compiler. Verible's `typedef-enums` (enabled by default) asks for the \
`typedef`, and lucisv checks the same shape.\n\n\
Every declaration is judged: a variable, a port, a struct member. \
There is no fix — where the `typedef` should go (this file, the \
package next to it) is a design decision, not a rewrite."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_declared_types(ctx.file(), &mut |declared| {
if !matches!(declared.ty.inline(), Some(TypeExtra::Enum(_))) {
return;
}
out.push(Violation::new(
NAME,
format!(
"`{}` is declared with an anonymous enum; name it with `typedef`",
declared.name
),
declared.span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
TypedefEnums.check(&LintContext::new(src, None))
}
#[test]
fn flags_an_anonymous_enum_variable_and_points_at_the_name() {
let src = "module m;\n enum logic [1:0] { IDLE, BUSY } state;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "state");
assert!(found[0].fix.is_none());
}
#[test]
fn a_typedef_enum_is_the_shape_it_asks_for() {
let src = "package p;\n typedef enum logic [1:0] { IDLE, BUSY } state_e;\nendpackage\n\
module m;\n state_e state;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_port_and_a_struct_member_are_covered() {
let src = "module m (input enum logic { A, B } mode);\nendmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
let src = "package p;\n typedef struct packed {\n\
\x20 enum logic { A, B } inner;\n } outer_t;\nendpackage\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_variable_declared_in_a_procedure_is_covered() {
let src = "module m;\n initial begin\n enum logic { A, B } local_state;\n end\n\
endmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn an_ordinary_declaration_is_none_of_its_business() {
assert!(violations("module m;\n logic [1:0] state;\nendmodule\n").is_empty());
let src = "module m;\n struct packed { logic a; } s;\nendmodule\n";
assert!(violations(src).is_empty(), "structs are the other rule's");
}
}
@@ -0,0 +1,144 @@
//! `typedef-structs-unions` — a `struct`/`union` type is declared with a
//! `typedef`.
use crate::context::LintContext;
use crate::decls::walk_declared_types;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::TypeExtra;
/// See [`Rule::doc`].
pub struct TypedefStructsUnions;
const NAME: &str = "typedef-structs-unions";
impl Rule for TypedefStructsUnions {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"give a struct or union type a name with `typedef`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"An anonymous `struct packed { … } s;` cannot be passed to a function, \
returned from one, carried on a port or written in a cast, and a \
second variable declared with the same member list is a *different* \
type to the compiler — so the layout ends up copied, and the copies \
drift. Verible's `typedef-structs-unions` (enabled by default) asks \
for the `typedef`, and lucisv checks the same shape on every \
declaration: a variable, a port, a member.\n\n\
The `allow_anonymous_nested` option exempts an anonymous aggregate \
written **inside** another aggregate's body, where it has a name — its \
member's — and cannot be referred to from outside anyway. Verible \
defaults its equivalent (`allow_anonymous_nested_type`) to false; \
lucisv defaults it to **true**, a deliberate divergence: on opentitan \
every one of the rule's 3 159 findings was a nested struct inside a \
`typedef` in a generated register package, and opentitan's own \
Verible config disables the whole rule for that reason. Set the \
option to false for Verible's stricter reading. There is no fix: \
where the `typedef` belongs is a design decision."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "allow_anonymous_nested",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "accept an anonymous struct or union written inside another one (lucisv's default; Verible's is false)",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let allow_nested = ctx.option_bool(NAME, "allow_anonymous_nested");
let mut out = Vec::new();
walk_declared_types(ctx.file(), &mut |declared| {
let Some(TypeExtra::Struct(structure)) = declared.ty.inline() else { return };
if declared.nested && allow_nested {
return;
}
out.push(Violation::new(
NAME,
format!(
"`{}` is declared with an anonymous {}; name it with `typedef`",
declared.name, structure.kw
),
declared.span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
TypedefStructsUnions.check(&LintContext::new(src, None))
}
#[test]
fn flags_an_anonymous_struct_and_points_at_the_name() {
let src = "module m;\n struct packed { logic a; } s;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("anonymous struct"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "s");
assert!(found[0].fix.is_none());
}
#[test]
fn a_union_is_named_in_the_message() {
let src = "module m;\n union packed { logic a; logic b; } u;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("anonymous union"), "{}", found[0].message);
}
#[test]
fn a_typedef_struct_is_the_shape_it_asks_for() {
let src = "package p;\n typedef struct packed { logic a; } word_t;\nendpackage\n\
module m;\n word_t w;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_nested_anonymous_struct_is_allowed_by_default_and_reported_when_asked() {
// lucisv's default is `allow_anonymous_nested = true` (the doc says
// why); Verible's stricter reading is one option away.
let src = "package p;\n typedef struct packed {\n\
\x20 struct packed { logic x; } inner;\n } outer_t;\nendpackage\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
let mut options = RuleOptions::new();
options.set_raw(NAME, "allow_anonymous_nested", "false").expect("accepted");
let ctx = LintContext::new(src, None).with_options(&options);
let found = TypedefStructsUnions.check(&ctx);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "inner");
}
#[test]
fn allowing_nested_ones_does_not_allow_a_top_level_one() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "allow_anonymous_nested", "true").expect("accepted");
let src = "module m;\n struct packed { logic a; } s;\nendmodule\n";
let ctx = LintContext::new(src, None).with_options(&options);
assert_eq!(TypedefStructsUnions.check(&ctx).len(), 1);
}
#[test]
fn an_anonymous_enum_is_the_other_rules_business() {
let src = "module m;\n enum logic { A, B } e;\nendmodule\n";
assert!(violations(src).is_empty());
}
}
+31
View File
@@ -142,6 +142,37 @@ fn stmts(list: &[Stmt], f: &mut dyn FnMut(&Stmt)) {
}
}
/// Calls `f` on every generate block of the file — the `begin … end` (or the
/// single item standing for one) of an `if`, `for` or `case` generate,
/// nested blocks included.
pub(crate) fn walk_generate_blocks(file: &SourceFile, f: &mut dyn FnMut(&GenBlock)) {
walk_items(file, &mut |item| match &item.kind {
ItemKind::GenIf(gen_if) => {
f(&gen_if.then);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
f(&nested.then);
els = nested.els.as_deref();
}
GenElse::Block(block) => {
f(block);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => f(&gen_for.body),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
f(&case_item.body);
}
}
_ => {}
});
}
/// Calls `f` on every `#( ... )` parameter port of the file — a module header's
/// and a class header's alike, since both spell them with the same node.
pub(crate) fn walk_param_ports(file: &SourceFile, f: &mut dyn FnMut(&ParamPort)) {
+43 -1
View File
@@ -81,10 +81,11 @@ fn severity_entry(severity: Severity, order: u32) -> String {
/// One rule's toggle.
fn rule_entry(rule: &'static dyn Rule, order: u32) -> String {
let description = format!(
"**{severity}** — {summary}. {default}",
"**{severity}** — {summary}. {default}{options}",
severity = rule.severity().as_str(),
summary = rule.summary(),
default = default_sentence(rule),
options = options_sentence(rule),
);
format!(
" \"{id}\": {{\n\
@@ -106,6 +107,20 @@ fn rule_entry(rule: &'static dyn Rule, order: u32) -> String {
)
}
/// The options a rule takes, named in its description.
///
/// No setting is generated *per option* — `lucisv.lint.options` is one object
/// that carries them all, and 60 more entries in the Settings UI would bury
/// the toggles this file exists to produce. What the description owes the
/// reader is the words to type into that object, which is this.
fn options_sentence(rule: &dyn Rule) -> String {
let names: Vec<String> = rule.options().iter().map(|spec| format!("`{}`", spec.name)).collect();
match names.len() {
0 => String::new(),
_ => format!(" Options (set them in `#lucisv.lint.options#`): {}.", names.join(", ")),
}
}
/// 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 {
@@ -180,6 +195,33 @@ mod tests {
assert_eq!(found, expected);
}
/// A rule with options says so, and names them; a rule without says
/// nothing extra.
#[test]
fn a_rules_description_names_the_options_it_takes() {
let json = vscode_lint_settings();
assert!(
json.contains("Options (set them in `#lucisv.lint.options#`): `length`."),
"line-length's option"
);
assert!(
json.contains(
"`localparam_style`, `localparam_style_regex`, `parameter_style`, \
`parameter_style_regex`."
),
"parameter-name-style's four"
);
for rule in all_rules() {
let has = !rule.options().is_empty();
let entry = json
.split(&format!("\"{}\"", rule_setting(rule)))
.nth(1)
.and_then(|rest| rest.split("},").next())
.unwrap_or_default();
assert_eq!(entry.contains("Options (set them in"), has, "{}", rule.name());
}
}
#[test]
fn json_strings_are_escaped() {
assert_eq!(json_string("a\"b\\c"), "\"a\\\"b\\\\c\"");
@@ -0,0 +1,10 @@
#select always-comb
# both spellings of the implicit sensitivity list
module m;
always @(*) x = 1;
//^ 3 always-comb
always @* y = 2;
//^ 3 always-comb
always @(a or b) z = 3;
always_comb w = 4;
endmodule
@@ -25,7 +25,7 @@ package p;
endpackage
====
# every non-procedural scope is reached: interface
interface ifc;
interface ifc_if;
logic a;
;
//^ 3 empty-item
@@ -48,7 +48,7 @@ endmodule
====
# every non-procedural scope is reached: inside a generate-for body
module m;
for (genvar i = 0; i < 2; i++) begin : g
for (genvar i = 0; i < 2; i++) begin : g_loop
;
//^ 5 empty-item
end
@@ -56,7 +56,7 @@ endmodule
====
# `end;` after a generate block, and a run of null items after it
module m;
if (N > 1) begin : g1
if (N > 1) begin : g_one
wire x;
end;
//^ 6 empty-item
@@ -0,0 +1,40 @@
#select explicit-begin
# an unblocked body is wrapped, and an `else if` chain is not touched
module m;
initial begin
if (a) x = 1;
//^ 12 explicit-begin
else if (b) begin
x = 2;
end
end
endmodule
----
module m;
initial begin
if (a) begin x = 1; end
//^ 12 explicit-begin
else if (b) begin
x = 2;
end
end
endmodule
====
#select explicit-begin
#options explicit-begin.if_enable = false
# each construct has its own switch
module m;
initial begin
if (a) x = 1;
while (b) y = 2;
//^ 15 explicit-begin
end
endmodule
----
module m;
initial begin
if (a) x = 1;
while (b) begin y = 2; end
//^ 15 explicit-begin
end
endmodule
@@ -0,0 +1,42 @@
#select package-filename
#path rtl/other.sv
# a package that does not match its file name
package foo_pkg;
//^ 9 package-filename
endpackage
====
#select package-filename
#path rtl/foo_pkg.sv
# both conventional spellings are accepted
package foo_pkg;
endpackage
====
#select package-filename
#path rtl/foo_pkg.sv
# a package named without the suffix, in a `_pkg` file
package foo;
endpackage
====
#select package-filename
#path rtl/foo-pkg.sv
#options package-filename.allow-dash-for-underscore = true
# a dash stands for an underscore when the project says so
package foo_pkg;
endpackage
====
#select one-module-per-file
# every module after the first is reported
module a;
endmodule
module b;
//^ 8 one-module-per-file
endmodule
====
#select one-module-per-file
# a package and an interface beside one module are not modules
package p;
endpackage
module a;
endmodule
interface i;
endinterface
@@ -0,0 +1,35 @@
#select generate-label,generate-label-prefix
# an unlabelled generate block, and a labelled one with no prefix
module m;
if (A) begin
//^ 10 generate-label
wire a;
end
for (genvar i = 0; i < 2; i++) begin : lanes
//^ 42 generate-label-prefix
wire b;
end
endmodule
====
#select generate-label,generate-label-prefix
# the convention is clean
module m;
if (A) begin : g_a
wire a;
end else begin : gen_b
wire b;
end
endmodule
====
#select generate-label-prefix
#options generate-label-prefix.prefix = ["blk_"]
# the option replaces the accepted prefixes
module m;
if (A) begin : blk_a
wire a;
end
if (B) begin : g_b
//^ 18 generate-label-prefix
wire b;
end
endmodule
@@ -0,0 +1,41 @@
#select line-length
# a line past the default width is reported at the first column over it
module m;
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
//^ 101 line-length
endmodule
====
#select line-length
# a line at the limit is not over it
module m;
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
endmodule
====
#select line-length
#options line-length.length = 60
# the option narrows the limit
module m;
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
//^ 61 line-length
endmodule
====
#select line-length
#options line-length.length = 200
# and widens it
module m;
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
endmodule
====
#select line-length
# a line that is one unbreakable token is left alone, `;` or not
`include "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.svh"
module m;
`AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;
endmodule
====
#select line-length
# a long comment can be wrapped, so it is reported
module m;
endmodule
// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
//^ 101 line-length
@@ -0,0 +1,83 @@
#select signal-name-style
# ports and signals are judged where they are declared
module m (input logic clkIn, output logic data_o);
//^ 23 signal-name-style
logic dataValid;
//^ 9 signal-name-style
logic wr_ptr2;
endmodule
====
#select signal-name-style
#options signal-name-style.style_regex = "[a-z][a-zA-Z0-9]*"
# the option replaces the convention
module m;
logic dataValid;
logic data_valid;
//^ 9 signal-name-style
endmodule
====
#select interface-name-style
# an interface without the `_if` suffix
interface bus;
//^ 11 interface-name-style
endinterface
====
#select interface-name-style
# the convention, and a module the rule says nothing about
interface bus_if;
endinterface
module bus;
endmodule
====
#select macro-name-style
# the defined name is judged, not the uses
`define my_macro 1
//^ 9 macro-name-style
`define MY_OTHER(a) (a)
module m;
wire x = `my_macro;
endmodule
====
#select constraint-name-style
# a constraint that does not end in `_c`
class c;
rand int addr;
constraint addr_range { addr > 0; }
//^ 14 constraint-name-style
constraint addr_max_c { addr < 9; }
endclass
====
#select parameter-type-name-style
# a type parameter named like a type, and one not
class c #(type T = int, type item_t = int);
//^ 16 parameter-type-name-style
endclass
====
#select port-name-suffix
# each direction has its own suffixes
module m (input logic clk, input logic rst_ni, output logic data_o, inout wire sda);
//^ 23 port-name-suffix
//^ 80 port-name-suffix
endmodule
====
#select port-name-suffix
#options port-name-suffix.suffixes = ["_i", "_o"]
# shortening the list bans the active-low spellings
module m (input logic clk_i, input logic rst_ni, output logic data_o);
//^ 42 port-name-suffix
endmodule
====
#select banned-declared-name-patterns
# nothing is banned until the project says so
module m;
logic tmp_addr;
endmodule
====
#select banned-declared-name-patterns
#options banned-declared-name-patterns.patterns = ["tmp.*"]
# a banned name is reported where it is declared
module m;
logic tmp_addr;
//^ 9 banned-declared-name-patterns
logic keep_me;
endmodule
@@ -0,0 +1,29 @@
#select forbid-consecutive-null-statements
# a doubled `;` is reported and the extra one deleted
module m;
initial begin
x = 1;;
//^ 11 forbid-consecutive-null-statements
end
endmodule
----
module m;
initial begin
x = 1;
//^ 11 forbid-consecutive-null-statements
end
endmodule
====
#select forbid-consecutive-null-statements
# an empty `for` header holds no statements
module m;
initial for (;;) x = 1;
endmodule
====
#select forbid-consecutive-null-statements
# a lone null statement is another rule's business
module m;
initial begin
;
end
endmodule
@@ -0,0 +1,13 @@
#select posix-eof
# a terminated file is clean
#
# The other half of this rule — a file whose last line has no newline — cannot
# be written here: the harness rejoins every case body with a trailing newline,
# so no case input can lack one. It is pinned in the rule's own unit tests
# (`rules::posix_eof::tests`), fix included.
module m;
endmodule
====
#select posix-eof
# a file that is only a comment is terminated too
// nothing but a note
@@ -0,0 +1,32 @@
#select typedef-enums,typedef-structs-unions
# anonymous aggregates in declarations
module m;
enum logic [1:0] { IDLE, BUSY } state;
//^ 35 typedef-enums
struct packed { logic a; } s;
//^ 30 typedef-structs-unions
endmodule
====
#select typedef-enums,typedef-structs-unions
# a named type is the shape they ask for
package p;
typedef enum logic [1:0] { IDLE, BUSY } state_e;
typedef struct packed { logic a; } word_t;
endpackage
module m;
state_e state;
word_t w;
endmodule
====
#select typedef-structs-unions
#options typedef-structs-unions.allow_anonymous_nested = true
# a nested anonymous struct may be allowed; a top-level one is still not
package p;
typedef struct packed {
struct packed { logic x; } inner;
} outer_t;
endpackage
module m;
union packed { logic a; logic b; } u;
//^ 38 typedef-structs-unions
endmodule
+2 -2
View File
@@ -29,13 +29,13 @@ endmodule
====
# a verible waiver for a rule lucisv does not have is ignored
module m;
// verilog_lint: waive macro-name-style
// verilog_lint: waive explicit-function-lifetime
wire a;
endmodule
====
# lucisv's own spelling for an unknown rule is reported
module m;
// lucisv: waive macro-name-style
// lucisv: waive explicit-function-lifetime
//^ 3 unused-waiver
wire a;
endmodule
+47 -15
View File
@@ -20,6 +20,10 @@
//! - `#path <p>` — lint the source as if it were read from this file path.
//! - `#select ...` — comma-separated rule names, `lucisv check --select`
//! semantics (replaces the default rule set).
//! - `#options <rule>.<key> = <value>` — set one per-rule option for this
//! case, in the `lucisv.toml` spelling (`120`, `true`, `"[a-z]+"`,
//! `["a", "b"]`). Repeatable. A refused entry fails the case, so the
//! option's own validation is pinned here too.
//! - `#workspace [name,...]` — run the case as part of a *project*: the rules
//! that need a workspace default on, and a `MentionOracle` answers "yes,
//! some other file mentions this" for each listed name (an empty list is a
@@ -42,7 +46,7 @@ use std::path::PathBuf;
use vlog_formatter::{format_source, Config};
use vlog_linter::{
apply_fixes, lint, rule_by_name, select_rules, Applicability, LintContext, MentionOracle,
ParsedSource, Rule,
ParsedSource, Rule, RuleOptions,
};
use vlog_parser::LineIndex;
@@ -54,6 +58,8 @@ struct Case {
tolerant: bool,
path: Option<String>,
select: Vec<String>,
/// `#options`: what this case configured about its rules.
options: RuleOptions,
/// `#workspace`: `None` is a run with no oracle; `Some(names)` is a run
/// with one that says those names are mentioned in some other file.
workspace: Option<Vec<String>>,
@@ -111,6 +117,7 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
let mut tolerant = false;
let mut path = None;
let mut select = Vec::new();
let mut options = RuleOptions::new();
let mut workspace = None;
let mut body = block;
while let Some(first) = body.first() {
@@ -129,6 +136,9 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
path = Some(p.trim().to_string());
} else if let Some(s) = rest.strip_prefix("select ") {
select = s.split(',').map(|r| r.trim().to_string()).collect();
} else if let Some(entry) = rest.strip_prefix("options ") {
set_option(&mut options, entry)
.map_err(|e| format!("{file}:{start}: bad #options: {e}"))?;
} else if rest == "workspace" {
workspace = Some(Vec::new());
} else if let Some(s) = rest.strip_prefix("workspace ") {
@@ -146,7 +156,7 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
} else if directive_like {
return Err(format!(
"{file}:{start}: unknown directive `#{}` \
(known: #path, #select, #workspace, #tolerant, #SKIP; \
(known: #path, #select, #options, #workspace, #tolerant, #SKIP; \
a case name needs a space after `#`)",
rest.split_whitespace().next().unwrap_or(rest)
));
@@ -169,7 +179,20 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
if input.trim().is_empty() {
return Err(format!("{file}:{start}: case has no source"));
}
Ok(Case { name, line: start, skip, tolerant, path, select, workspace, input, fixed })
Ok(Case { name, line: start, skip, tolerant, path, select, options, workspace, input, fixed })
}
/// One `#options <rule>.<key> = <value>` entry, through the linter's own
/// validator — the same door a `lucisv.toml` comes in by.
fn set_option(options: &mut RuleOptions, entry: &str) -> Result<(), String> {
let (name, value) = entry
.split_once('=')
.ok_or_else(|| format!("expected `<rule>.<key> = <value>`, found `{entry}`"))?;
let (rule, key) = name
.trim()
.split_once('.')
.ok_or_else(|| format!("expected `<rule>.<key>`, found `{}`", name.trim()))?;
options.set_raw(rule.trim(), key.trim(), value.trim())
}
/// Attaches the case's oracle, if it declared one.
@@ -238,14 +261,17 @@ fn check_case(file: &str, case: &Case) -> Result<(), String> {
let path = case.path.clone().map(PathBuf::from);
let oracle = case.workspace.clone().map(Elsewhere);
let own = LintContext::new(&case.input, path.clone());
let own = LintContext::new(&case.input, path.clone()).with_options(&case.options);
let violations = lint(&with_oracle(own, oracle.as_ref()), &rules);
// "One parse, two tools", held over every case: a context built from
// pre-parsed products must find exactly what one built from the source
// does — rule, message, span and fix alike (the Debug form carries all).
let parsed = ParsedSource::parse(&case.input);
let via_products = lint(&with_oracle(parsed.context(path.clone()), oracle.as_ref()), &rules);
let via_products = lint(
&with_oracle(parsed.context(path.clone()).with_options(&case.options), oracle.as_ref()),
&rules,
);
if format!("{violations:?}") != format!("{via_products:?}") {
return Err(format!(
"{at}: linting from pre-parsed products found something different from \
@@ -334,12 +360,16 @@ fn check_fix(
oracle: Option<&Elsewhere>,
expected_fixed: &str,
) -> Result<(), String> {
let options = &case.options;
let mut fixed = case.input.clone();
for round in 0.. {
if round >= 10 {
return Err(format!("{at}: fixing did not settle within 10 rounds"));
}
let found = lint(&with_oracle(LintContext::new(&fixed, path.clone()), oracle), rules);
let found = lint(
&with_oracle(LintContext::new(&fixed, path.clone()).with_options(options), oracle),
rules,
);
let out = apply_fixes(&fixed, &found, false);
if out.applied == 0 {
break;
@@ -357,15 +387,17 @@ fn check_fix(
// offer a Safe fix — a violation without a fix (or with an Unsafe one)
// may legitimately survive.
let index = LineIndex::new(&fixed);
let still_fixable: Vec<String> =
lint(&with_oracle(LintContext::new(&fixed, path.clone()), oracle), rules)
.iter()
.filter(|v| v.fix.as_ref().is_some_and(|f| f.applicability == Applicability::Safe))
.map(|v| {
let (line, col) = index.line_col(v.span.start);
format!(" {line}:{col} {} — {}", v.rule, v.message)
})
.collect();
let still_fixable: Vec<String> = lint(
&with_oracle(LintContext::new(&fixed, path.clone()).with_options(options), oracle),
rules,
)
.iter()
.filter(|v| v.fix.as_ref().is_some_and(|f| f.applicability == Applicability::Safe))
.map(|v| {
let (line, col) = index.line_col(v.span.start);
format!(" {line}:{col} {} — {}", v.rule, v.message)
})
.collect();
if !still_fixable.is_empty() {
return Err(format!(
"{at}: the fixed output still has Safe-fixable findings:\n{}",
+837
View File
@@ -0,0 +1,837 @@
# linter expansion, wave 2 — per-rule options and the first Style rules
## Goal
TODO §34. Two things: the **option plumbing** every configurable rule needs
(`OptionSpec`/`OptionKind`/`OptionValue`/`RuleOptions` in `vlog_linter`,
`Rule::options()`, `LintContext` access with the spec default as the
fallback, `[lint.<rule>]` tables in `lucisv.toml`, a `lucisv.lint.options`
object in the editor, precedence editor over toml over default), and the
**eighteen Style rules** from Verible's list that carry the most weight in a
style guide — naming, file layout, generate labels, typedefs, line length.
The four naming rules that predate options gain the options Verible gives
them, with defaults that reproduce today's behaviour exactly. The registry
goes from 36 rules to 54.
## Assumptions
- **Verible is the reference for names and defaults.** Every rule cites its
Verible equivalent in its `doc` and takes Verible's option spelling. The
reference was read at
<https://chipsalliance.github.io/verible/lint.html> during the round, not
from memory: `typedef-structs-unions`' option really is
`allow_anonymous_nested` (default false), `line-length` really is `length`
(100), `package-filename` really is `allow-dash-for-underscore` (false),
and `parameter-name-style` really takes exactly the four keys used here.
Every deviation is listed in the work log and named in the rule's own
`doc`.
- **A pattern is not RE2.** `crates/vlog_linter/src/regex.rs` implements the
subset a style guide is written in — literals, `.`, `[...]` classes, the
escapes `\d \D \w \W \s \S \n \t \r` and `\<punctuation>`, groups,
`|`, and the postfix `*` `+` `?` — matched anchored at both ends.
Everything else is refused **when the option is read, by name**: counted
repetition, `(?...)` groups, and every escape the engine does not
implement (`\b`, `\1`, `\A`, `\p{…}`, `\x41`). Justification for not
taking a `regex` dependency: this crate depends on `vlog_parser` + `std`
alone, and the whole engine is one file with its own tests. The cost is
that a project using a backreference or a lookahead in a Verible
`style_regex` gets an error instead of a rule; no such pattern appears in
Verible's own defaults.
- **No pattern can hang a run.** The matcher is a Thompson-NFA simulation
(a Pike VM without captures): the live set of program counters is
advanced one character at a time, each state entered at most once per
character, so matching is `O(pattern × name)` **by construction**. This
replaced a backtracking matcher that was exponential on an ambiguous
repeat — see the rework entry of 2026-09-04.
- **A rule never sees "unset".** Every read falls back to the spec's
declared default; `is_set` exists for the one rule whose fallback is not a
constant (`line-length` follows the formatter's width) and for the two
`*_style_regex` overrides, where "unset" means "the words decide".
- **Defaults reproduce today's findings character for character.** Where a
preset became a pattern, a default run still prints the preset's sentence
(`naming::style_message`); only a configured run names the pattern. Proved
by diffing the whole finding list against the 0.36.0 binary — see
Measurements.
- The **structure-reading** new rules (`generate-label`,
`generate-label-prefix`, `one-module-per-file`, `package-filename`) are
silent in a file that does not fully parse, the discipline `context.rs`
documents for `duplicate-declaration`. The naming rules are not: a
declaration recovery bound in the wrong scope still *is* a declaration
with that name, so the finding stays true.
## Handshakes
- **Consumed** — `vlog_parser::ast` (unchanged), `vlog_semantic::Semantics`
(`symbols()` for `banned-declared-name-patterns`), `lucisv_core::config`'s
parser shape, `vlog_formatter::Config::max_width` (the width
`line-length` follows).
- **Promised (new public API of `vlog_linter`)** — `OptionSpec`,
`OptionKind`, `OptionValue`, `OptionDefault`, `RuleOptions`,
`Rule::options()` (default empty, so no rule outside this round changes),
`LintContext::with_options` / `with_line_length` (both optional; a caller
that lends neither gets exactly the shipped behaviour).
- **`lucisv_core::config`** — `FileConfig` gains `lint_options:
Vec<LintOption>` (rule, key, raw text, line) and `source:
Option<PathBuf>`, the file a config was read from, so an error about an
entry can name the file to edit. `[lint.<rule>]` is now **accepted**
rather than rejected by name; the old "per-rule lint settings are not
supported yet" error is gone, and the test that pinned it now pins the
malformed-header errors instead.
- **Files touched outside the brief's list, both minimal and pre-agreed or
forced:**
- `crates/lucisv_server/src/server/notification.rs` — the three-line
`window/logMessage` loop for refused `lucisv.lint.options` entries
(pre-agreed by the lead in the resume brief), plus one comment.
- `crates/lucisv/src/main.rs` — `stdin_config` now returns the
`FileConfig` beside the `Config` so a stdin buffer can read the same
`[lint.<rule>]` tables a file does, and the stdin lint path builds the
options. Unavoidable: `lint::check_stdin` gained a parameter.
- **Not changed, deliberately:** `vlog_formatter` and `verify.rs` (untouched
— the formatter's corpus output is byte-identical to 0.36.0),
`lucisv_server/src/format.rs` (its ladder is cited, not altered).
## Status / TODO
- [x] 34.0(a) `options.rs` + `regex.rs`; `Rule::options()`;
`LintContext::with_options`/`with_line_length` and the `option_*`
accessors; registry table tests
- [x] 34.0(b) `[lint.<rule>]` tables stored raw in `lucisv_core::config`;
the CLI resolves them per file and fails with `file:line`
- [x] 34.0(c) `lucisv.lint.options` in the editor, validated the same way;
a bad entry is dropped and logged
- [x] 34.0(d) precedence editor > toml > default, key by key
- [x] 34.0(e) `--rules-doc` lists every option with kind, default and doc;
each toggle's description names the options its rule takes
- [x] 34.0(f) pins: parse/validate tables, a `lucisv.toml` that changes the
verdict, the editor object over the wire, a bad key naming file:line
- [x] 34.1 options on the four naming rules; finding lists byte-identical
- [x] 34.2 the eighteen Style rules, each with tests, a `.lint` case,
corpus + opentitan counts and ten classified findings
- [x] 34.3 docs (README "Linting", `editors/vscode/README.md`, the
docs-site rules page) + regenerated `package.json`
- [x] Gates (guarded): fmt, clippy 0, `cargo test --workspace` 3 549/48
binaries, corpus 814/820, `--stdout` byte-identity 0 differing, vsix
smoke, opentitan census + timing
- [ ] QA
## The rules, measured
Counts are `lucisv check --select <rule> --no-config` over the 860-file
corpus and over `~/repo/opentitan/hw` (10 k files, read-only). "V" is
Verible's default for the same rule; where lucisv differs, why is in the
row. Ten findings per rule were read; the classification column says what
they were.
| Rule | Sev | Default (V→here) | Verible equivalent | Options (default) | Corpus | opentitan | Ten findings read |
|---|---|---|---|---|---|---|---|
| `line-length` | style | on→on | `line-length` | `length` (formatter's width, else 100) | 225 | 375 | 10 true. All real over-runs; 101 of the 104 in `rtl/` are auto-generated (`lc_ctrl_state_pkg`, `rtl/autogen/*`), 2 are a 101-char comment duplicated in `tlul_adapter_{vh,shim}.sv` — genuine, and Verible at opentitan's own `line-length=length:100` would report them too |
| `posix-eof` | style | on→on | `posix-eof` | — | 0 | 1 | 1 true (all there is): `pulp_riscv_dbg/src/dmi_test.sv` really has no final newline. The corpus has none — every file in it ends properly |
| `forbid-consecutive-null-statements` | style | on→on | same | — | 2 | 1 | 3 true (all there are): a literal `;;` after a `$error(…)` and after two declarations in `cb_filter_tb` |
| `generate-label` | style | on→on | `generate-label` | — | 36 | 3 | 10 read (3 on opentitan, 7 more on the corpus), all true: real unlabelled `if`/`for` generate blocks in `common_cells` and ibex fcov, and a `generate for … begin` in `dm_top_sva`. 177 phantoms from two unparsable UVM files were closed by the `parsed_cleanly` gate |
| `generate-label-prefix` | style | on→on | same | `prefix` (`["g_","gen_"]`) | 0 | 0 | **0 findings on either tree** — every labelled generate block in both writes `g_`/`gen_`. Behaviour pinned by unit tests and three `.lint` cases instead, the option included |
| `package-filename` | style | on→on | same | `allow-dash-for-underscore` (false) | 1 | 0 | 1 true, needs judgment (all there is): `common_cells/include/common_cells/assertions.svh` declares `assert_rpt_pkg`. A package in an `.svh` include is a deliberate shape; Verible reports it too, and `--ignore` or a waiver is the answer |
| `one-module-per-file` | style | off→off | same | — | 37 | 10 | 10 true: `aes_sbox_*`, `spi_host_data_stable_sva` really declare a second module. Off, as Verible ships it |
| `signal-name-style` | style | off→off | same | `style_regex` (`[a-z_0-9]+`) | 72 | 374 | 10 true: `clk_48MHz_i`, `IO_CLK`, `ReadyIsStable`, `stL`, `cfg_prefix_6B_i` |
| `interface-name-style` | style | on→on | same | `style_regex` (`[a-z_0-9]+(_if)`) | 5 | 6 | 10 read (6 + 4 more, one overlapping), all true: `STREAM_DV`, `DMI_BUS_DV`, `JTAG_DV`, `ibex_mem_intf`, `mem_assume_t`. Every one is vendored code, outside opentitan's own filesets |
| `macro-name-style` | style | on→on | same | `style_regex` (`[A-Z_0-9]+`) | 18 | 12 | 10 true: `` `define uvm_object_new``, `` `define add_instr(...)``. All in `dv/` and `vendor/`, which opentitan's RTL lint does not cover |
| `constraint-name-style` | style | on→on | same | `pattern` (`([a-z0-9]+_)+c`) | 15 | 19 | 10 true: the `c_`-prefixed UVM convention (`c_clen`, `c_delay_dist`) is the mirror image of Verible's `_c` suffix. All in `dv/`+`vendor/` |
| `parameter-type-name-style` | style | off→off | same | `style_regex` (`[a-z][a-z_0-9]*_t`) | 81 | 133 | 10 true: `type CFG_T`, `type RAL_T` — the UVM convention the rule's doc predicts, which is why it ships off |
| `port-name-suffix` | style | off→off | same | `suffixes` (the six) | 1 129 | 1 843 | 10 true: `input active`, `input clk`, `output dmi_req_valid`. Off, as Verible ships it |
| `banned-declared-name-patterns` | style | off→off | same | `patterns` (empty) | 0 | 0 | **0 by construction** — an empty list reports nothing and the rule returns before touching the symbol table. Behaviour pinned by unit tests and two `.lint` cases with `patterns` set |
| `typedef-enums` | style | on→on | same | — | 6 | 4 | 10 read (4 + 6), all true: anonymous state enums declaring two variables at once (`state, state_next`, `CS, NS`), reported per declarator |
| `typedef-structs-unions` | style | on→on | same | `allow_anonymous_nested` (false) | 69 | 3 159 | 10 true (the corpus's 69 are the same shape — a vendored copy of `uart_reg_pkg`). **All 3 159 are nested anonymous structs inside a `typedef`, in 57 `reggen`-generated register packages.** opentitan's own Verible config disables the rule (`-typedef-structs-unions`, "we allow nested struct definitions"); here `allow_anonymous_nested = true` expresses the same choice and takes the file that produced 32 findings to 0 |
| `always-comb` | style | on→on | same | — | 23 | 13 | 10 read: 4 true (`always @( * )` / `always (* xprop_off *) @( * )` in the `ast` behavioural models, outside the RTL filesets), 6 **needs judgment** — all in plain Verilog-2001 `.v` files (`picorv32.v`, `prim_clock_gating.v`) where `always_comb` may not be available to the project's toolchain. Verible reads every file as SystemVerilog and reports the same; the fix is unsafe, and a Verilog-2001 codebase turns the rule off with one `ignore` |
| `explicit-begin` | style | off→off | same | eleven `*_enable` (all true) | 1 093 | 4 291 | 10 true: `if (active) initialize();`, `always_comb x = …;`. Off, as Verible ships it |
Why a Verible-default rule fires inside opentitan at all: opentitan lints
`hw/ip/*/rtl` filesets with `hw/lint/tools/veriblelint/lowrisc-styleguide.
rules.verible_lint`, which **disables `typedef-structs-unions` outright**,
sets `line-length=length:100` (the same limit lucisv uses) and sets
`parameter-name-style=localparam_style:CamelCase|ALL_CAPS` — the very
default §34.1 chose here over Verible's stricter `CamelCase`. `dv/`, `tb/`,
`pre_dv/` and `vendor/` are not in those filesets, which is where most of
the remaining findings live.
The default set therefore reports **4 212 findings on opentitan `hw/`**
against 0.36.0's 619; the difference is exactly the twelve new default-on
rules (3 159 + 375 + 19 + 13 + 12 + 6 + 4 + 3 + 1 + 1 = 3 593), and 3 159 of
those are the one rule opentitan turns off in its own config.
## Work log
### 2026-09-03 — dev (Opus 5), first sitting (paused mid-round)
Wrote 34.0(a) (`options.rs`, `regex.rs`, `Rule::options`, the context
accessors) and 34.1 (the four naming rules), plus fifteen of the eighteen
rule files, none of them registered. Recorded at the pause in the
checkpoint commit `1d4bddf`. The two `OptionKind` additions proposed then —
`RegexList` and `Words` — were accepted by the lead on resume.
### 2026-09-04 — dev (Opus 5), second sitting (round finished)
**34.2 finished.** Registered all eighteen rules alphabetically in
`rules/mod.rs` and `registry::all_rules`, declared `mod module_decls`, and
wrote the three that were missing: `typedef-structs-unions`, `always-comb`
(unsafe fix, replacing exactly the `always @(*)` header read off the tokens
so a comment inside the control is not silently dropped) and
`explicit-begin` (Verible's eleven `*_enable` options, safe fix wrapping the
body — statement spans include the terminating `;`, verified before relying
on it).
Registration surfaced four real problems, all fixed:
1. `module_signals` collected a non-ANSI port **twice** — once from the
header's name list, once from the body's `input x;`. The header list is
now skipped: a non-ANSI header names ports, the body declares them, and
the declaration is what a rule should point at.
2. A nested `module` is illegal SystemVerilog, so the parser recovers by
promoting it to file scope. `one-module-per-file` would have accused the
author of a second module; it now asks `parsed_cleanly` first.
3. `generate-label` produced **177 of its 180 opentitan findings** from two
files error recovery could not put back together, where a procedural
`if (…) begin` is rebound as a generate block. Both generate rules (and
`package-filename`, for the same reason) now ask `parsed_cleanly`. This
is the false-positive class `context.rs` documents for
`duplicate-declaration`, met again — worth its own line in the next
round's brief.
4. Two existing `.lint` cases and one unit test named `macro-name-style` as
a rule lucisv does not have. They now name `explicit-function-lifetime`
(§35's), and three case sources gained the labels/suffixes the new
default-on rules ask for.
**34.0(b)–(e) written.** `lucisv_core::config` grew `Table::Rule(name)` and
stores each entry raw with its line; `FileConfig` records the file it came
from. `lucisv check` resolves them per file through `RuleOptions::set_raw`
and fails with `<config>:<line>: <message>` on the first bad entry — the
same treatment a bad `[lint] select` name gets. The editor's
`lucisv.lint.options` goes through `RuleOptions::set` (one validator, two
front ends); a refused entry is dropped, described, and logged by
`apply_settings`. `lint_selection` gained the options, so changing one
republishes every open file exactly as changing a toggle does.
`--rules-doc` prints an option table per rule; the VS Code generator names
each rule's options in its description and `package.json` was regenerated
from it (the drift test proves it).
**Decisions and deviations, for the lead:**
- **`OptionKind` has seven members**, not the plan's five: `RegexList` (so
`banned-declared-name-patterns`' entries are validated as patterns) and
`Words(&[&str])` (so `parameter_style: CamelCase|ALL_CAPS` is validated
against a vocabulary — a plain `Str` would accept `snake_case` and then
match nothing). Accepted by the lead on resume.
- **Naming defaults are stricter than Verible's, on purpose.**
`enum-name-style` defaults to `[a-z][a-z_0-9]*(_t|_e)` where Verible has
`[a-z_0-9]+(_t|_e)`; `struct-union-name-style` to `[a-z][a-z_0-9]*_t`;
`module-name-style` to `[a-z][a-z_0-9]*`. Verible's own patterns accept a
leading `_` or digit, which the presets these replaced rejected — and
§34.1 requires the finding lists to be byte-identical. Each rule's `doc`
says so.
- **`parameter-name-style` keeps `CamelCase|ALL_CAPS` for `localparam`**
where Verible defaults to `CamelCase`. The reason was already in the
rule's doc; opentitan's own Verible config makes the same change, which
is as good a vindication as this round could hope for.
- **Options lucisv adds where Verible has none:** `generate-label-prefix`'s
`prefix` (§34 asked for it), `parameter-type-name-style`'s and
`struct-union-name-style`'s `style_regex` (§34.1 asked for the latter;
Verible spells its own as `exceptions`), `port-name-suffix`'s `suffixes`,
`banned-declared-name-patterns`' `patterns`.
- **`.lint` harness**: added a `#options <rule>.<key> = <value>` header, so
an option-driven case is pinned in the table harness through the same
validator a `lucisv.toml` uses. 246 cases, all green.
- **`posix-eof` has no marker case**: the harness rejoins every case body
with a trailing newline, so no case input can lack one. Pinned in the
rule's unit tests instead, fix included; the case file says so.
- **Editor beats `lucisv.toml` for options, key by key** — the opposite of
`format::settings_for`'s ladder for formatting. Instructed by §34.0(d)
and the resume brief; the reason (formatting has a byte-exact contract
with CI, a lint option changes what one user is shown) is written into
`lint::configured`'s doc comment, README.md and the extension README so
nobody has to re-derive it.
- **`line-length`'s width** follows the *formatting* ladder instead
(`lucisv.toml` > editor > 100), because it is not a lint setting but the
width the formatter would wrap to; the rule's own `length` option beats
it either way.
- The server reads the buffer's `lucisv.toml` once per lint pass, as
`format::discover` does per formatting request. A few `stat`s beside the
parse and analysis that pass already pays for; a `lucisv.toml` edited
while the server runs takes effect at the next publish.
- `naming::is_lower_snake_case` lost its last caller and was deleted; a
test now proves the pattern that replaced it accepts exactly the same
names.
### 2026-09-04 — dev (Opus 5), rework after QA's REWORK verdict
Both HIGH findings were in `crates/vlog_linter/src/regex.rs`; nothing else
QA raised needed a code change.
**(1) Catastrophic backtracking — root cause.** The matcher was a
continuation-passing **backtracking** search: `matches()` tried a repeat
greedily and handed the rest of the pattern a continuation to fail back
into. For an unambiguous pattern that is fine, and every default this round
ships is unambiguous (QA measured all four at sub-2 µs on 100-character
names). For an *ambiguous* one — `(a*)*b`, where the inner and outer repeats
can split the same run of `a`s in exponentially many ways — every split is
tried before the match fails, which is `2^n` in the name's length: QA
measured 20 ms / 648 ms / 20.6 s at 20 / 25 / 30 characters and a
`tools/guard.sh -t 15` kill on the shipped binary. The zero-width guard in
`repeat()` stopped an *infinite* loop and said nothing about an exponential
one. Worse, `OptionKind::Regex` accepts such a pattern happily, so a
`lucisv.toml` or an editor setting could configure the hang into every
future lint run and every keystroke-triggered republish.
The fix is structural, as the brief required: the parser is unchanged (so
every error message survives), but its tree is now **compiled to a small
instruction program** (`Char`/`Any`/`Class`/`Split`/`Jump`/`Match`) and run
as a **Thompson-NFA simulation** — the set of live program counters is
advanced one character at a time, with a per-character `seen` array that
enters each state at most once. That makes the cost `O(prog × name)`
whatever the pattern is: no backtracking, no continuation, nothing to
explode. `Regex::compile` / `Regex::is_match` keep their signatures and
whole-name semantics, so no rule and no caller changed.
Measured after: the six ambiguous shapes (`(a*)*b`, `(a|aa)*b`, `(.*)*x`,
`((a*)*)*b`, `(a+)+b`, `(a?)*b`) over a **200**-character name are asserted
under 500 ms in a unit test (they take microseconds); QA's own end-to-end
reproduction — a `lucisv.toml` with `style_regex = "(a*)*b"` and a file
declaring a long `a…a` wire — now runs under `tools/guard.sh -m 1 -t 5`
with no kill, and stays flat as the name grows: **n = 20 / 25 / 30 / 200 /
1000 characters all at 1.07 s wall**, which is `guard.sh`'s own one-second
polling floor rather than lucisv's time (exit 1, findings reported, never
137).
**(2) Unsupported escapes read as literals — root cause.** `escape()` and
`class_escape()` each matched the escapes they implement and then fell
through to `other => Node::Char(other)`, i.e. "any escape I do not know is
that character". That is the ordinary rule for `\.` or `\[`, and quietly
wrong for a letter or digit escape from another dialect: `(a)\1` compiled
and matched the literal `a1`, and `\bword\b` — an RE2 word boundary, and
RE2 is exactly what Verible's `style_regex` values are written in —
compiled and matched the literal `bwordb`. A user pasting a Verible pattern
got a naming rule that judged the wrong names with no diagnostic at all,
contradicting this README's own "refused by name" assumption.
Now the fallback splits: an escaped character that `is_alphanumeric()` and
is not one of the nine implemented (`d D w W s S n t r`) is an error naming
it and listing what is supported; everything else (punctuation, symbols)
stays the literal it has always been. Inside a `[...]` class the same rule
applies, with `\D`/`\W`/`\S` refused separately and specifically —
a class here is one range set with one negation flag, and mixing a
complemented set into it would need set arithmetic this engine does not do,
so it says so rather than guessing. `(?...)` groups are refused by name too
(they used to reach the `?`-has-nothing-to-repeat error, which named the
wrong thing).
Both front ends surface it unchanged: the CLI prints
`<config>:<line>: rule `signal-name-style` `style_regex`: `\bword\b` is
not a valid pattern: unsupported escape `\b` (supported: …)` — the rule
name is new, added so an error read out of a CI log stands without its
table header — and the editor logs
`lucisv.lint.options.signal-name-style.style_regex: … ; ignored` and keeps
the rule running on its default.
**Cross-check.** The probe table is now a unit test of **71** (pattern,
text, expected) rows — QA's categories (literals, `.`, classes with ranges
and negation, `\d\w\s` and their negations, groups, alternation, `*+?`,
nested and empty alternatives, anchoring) plus the ambiguous-repeat shapes
this rework exists for — and every row was verified against CPython's
`re.fullmatch` before being written down: **71/71 agree**, and the Rust test
asserts the engine reproduces the same table. QA's two escape cases are the
first two rows of the refusal test: `(a)\1` and `\bword\b` no longer
compile at all, so neither can match `a1` or `bwordb`.
**Gates re-run after the rework** (all guarded): fmt; clippy **0
warnings**; `cargo test --workspace` **3 549 passed / 0 failed / 42 ignored
/ 48 binaries** (unchanged — four narrow regex tests were folded into the
71-row probe table, and one option test was added); corpus gate
`{"passing":814,"total":820}`; `--stdout` over 860 corpus files vs 0.36.0
**0 differ**; **34.1 identity re-proved** (corpus 43, opentitan 35, stdout
and stderr byte-identical); the full 18-rule opentitan census
**identical to the pre-rework run**, 10 244 findings — the engine swap
changed no verdict anywhere; vsix smoke OK; `git -C ~/repo/opentitan status
--porcelain` still only the three pre-existing files.
**Not changed.** QA's LOW coverage note (no checked-in `tests/e2e.rs` case
for `lucisv.lint.options` over the wire) and the `tools/guard.sh` stdin
observation are left for the lead: the first is a test to add in another
lane's file, the second is outside §34's file list.
## Measurements
All runs under `tools/guard.sh`; no guard kill at any point.
- **`cargo test --workspace`**: **3 549 passed, 0 failed, 42 ignored** over
48 test binaries (baseline 3 393 over the same 48 binaries, 42 ignored) —
+156 tests, no binary added or removed. (The brief's "48" is the number of
test binaries; the ignored count has been 42 since §33.)
- **fmt**: `cargo fmt -p` for `vlog_linter`, `lucisv_core`, `lucisv`,
`lucisv_server`. **clippy**: `cargo clippy --all-targets --workspace`,
**0 warnings**.
- **Corpus gate**: `{"passing":814,"total":820,"pct":99.3}` — the same six
known failures, unchanged.
- **Formatter byte-identity**: `lucisv format --stdout` over all 860 corpus
files, this build vs `~/.cache/lucisv-baselines/lucisv-0.36.0`:
**0 differ**. The formatter was not touched.
- **34.1 byte-identity**: `check --select enum-name-style,struct-union-name-
style,module-name-style,parameter-name-style --no-config`, this build vs
0.36.0 — corpus **43 findings, byte-identical**; opentitan `hw/` **35
findings, byte-identical**, stderr included.
- **opentitan `check` timing** (three interleaved runs each, `/usr/bin/time
-p` inside the guard): 0.36.0 **0.91 / 0.87 / 0.90 s**, this build **0.89
/ 0.91 / 0.90 s** — no measurable difference, though the new build does
strictly more work (twelve more default-on rules).
- **vsix smoke**: `node editors/vscode/smoke.js target/debug/lucisv-server`
— OK, 20 messages.
- **opentitan tree after the round**: `git -C ~/repo/opentitan status
--porcelain` shows only the three pre-existing modifications
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
`hw/top_earlgrey/ip/ast/rtl/ast.sv`). Every opentitan run was read-only.
## QA log
### 2026-09-04 — QA (Sonnet 5)
Verified in the `lint-2` worktree only, everything guarded, opentitan
read-only. Scratch under `.../scratchpad/qa-34/`.
**1. Gates.** All guarded, all reproduced independently of the dev's own
numbers: `cargo fmt --all -- --check` clean; `cargo clippy --all-targets
--workspace` 0 warnings, and `git diff 10b63e6 --` shows no new `#[allow]`;
`cargo test --workspace --no-fail-fast` **3 549 passed / 0 failed / 42
ignored / 48 binaries**, exact match. `git diff --stat 10b63e6 --
crates/vlog_formatter crates/vlog_parser` empty. Corpus gate
`{"passing":814,"total":820}`, exact match. `--stdout` over the 860-file
corpus (this build vs `~/.cache/lucisv-baselines/lucisv-0.36.0`): **0
differ**. vsix smoke: OK, 20 messages. Changed-file set: every tracked file
in `git diff --stat 10b63e6` plus the two untracked-then-added rule files is
inside `vlog_linter`/the two disclosed handshake files
(`lucisv_server/src/server/notification.rs`, `lucisv/src/main.rs`) or the
brief's other named files; `vlog_linter/src/{decls,module_decls,naming,
visit}.rs` are touched but not individually named in TODO §34's file list —
not a violation, since they are inside the feature's own crate and the
work log's item 1–4 already explain each one (non-ANSI double-count,
`parsed_cleanly` gating, a dead helper's removal).
**2. The regex engine — two HIGH findings.**
Wrote 46 (pattern, text) probes (literals, `.`, classes with ranges and
negation, `\d\w\s` and their negations, groups, alternation, `*+?`, nested
groups, empty alternatives) and compared every verdict against Python's
`re.fullmatch` in a standalone copy of `regex.rs` (`pub(crate)` → `pub`,
compiled outside the crate so nothing in the dev worktree was touched): **46
/ 46 agree**. Anchoring confirmed: `abc` vs `xabcx` → false, `abc` vs `abc`
→ true, matching `regex.rs`'s own `the_match_is_anchored_at_both_ends`.
- **HIGH — catastrophic backtracking, reproduced end to end on the shipped
binary, guard-killed.** `(a*)*b` against a 20–30 `a`-character name with no
trailing `b` (a name length well inside normal signal-name territory):
20 chars → 20 ms, 25 → 648 ms, 30 → 20.6 s (roughly ×32 per +5 chars,
textbook exponential). Reproduced with the real binary, not just the
extracted copy: a `lucisv.toml` with `[lint.signal-name-style]
style_regex = "(a*)*b"` and a file declaring a 30-`a` wire, `tools/guard.sh
-t 15 -- lucisv check bad.sv` → **`guard.sh: 15 s exceeded — killing`**,
exit 137. `OptionKind::Regex`'s `check()` only calls `Regex::compile`,
which has no notion of pathological shape, so this pattern is accepted
by both front ends with no warning — a project or an editor session can
configure a hang into every future lint run, and the LSP server would
freeze on it on every keystroke-triggered republish. The eighteen new
rules' own *default* patterns were also timed against realistic 20–100
char non-matching names (`constraint-name-style`, `signal-name-style`,
`parameter-type-name-style`, `interface-name-style` defaults): all sub-2
µs even at 100 chars, so this is a risk in a **user-authored** pattern,
not in anything shipped. `crates/vlog_linter/src/regex.rs`'s `repeat()`
(lines 119–138) only guards against a zero-width iteration, which stops
`(a?)*b` from looping forever but does nothing about the ambiguous-split
blowup a pattern like `(X*)*` invites. No fix suggested here — flagging
for the lead to decide between a matched-position memo (early-exits the
classic case cheaply), a step budget, or documenting patterns of this
shape as refused by construction (e.g. reject a repeat whose body can
itself match zero-or-more of a single class, the RE2-style answer).
- **HIGH — unsupported escapes are silently accepted as a literal instead
of refused "by name."** The Assumptions section promises "anything else
is refused by name when the option is read." `escape()`
(`regex.rs:233–247`) and `class_escape()` (`regex.rs:289–309`) each have
an explicit list (`d D w W s S n t r`) and a fallback arm,
`other => Node::Char(other)`, that turns **every unrecognized escape**
into its own literal character. Concretely: `(a)\1` (a backreference)
compiles and matches the literal string `a1`; `\bword\b` (an RE2/Verible
word-boundary anchor — the assumption is explicit that "Verible spells
every naming convention as an RE2 pattern," and RE2 supports `\b`)
compiles and matches the literal string `bwordb`, not "word" with
boundaries. Both were probed with `Regex::compile` directly: no `Err`,
and `is_match` returns a plausible-looking but wrong verdict with no
diagnostic at all — exactly the failure mode the brief calls out ("never
silently mis-match"). A user who pastes a Verible `style_regex` containing
`\b`, `\B`, `\A`, `\Z`, `\1`–`\9`, or any other dialect escape gets a
naming rule that quietly accuses or excuses the wrong names, with no
error to notice. `{2,3}` and `(?=...)` **are** correctly refused by name
(confirmed both still error as documented); the gap is specifically the
escape fallback's catch-all.
**3. Options, both front ends.** CLI (`lucisv check` over a `lucisv.toml`):
verdict-changing confirmed (`length = 40` flags a 48-char line the default
100 does not); bad key → `` `<config>:5: rule `line-length` has no option
`lenght`; it has: length` ``; wrong kind →
`` `length` expects an integer, found `"10"` ``; out of range →
`` `length` must be between 40 and 400, found 999999` ``; bad regex →
`` `style_regex`: `[a-` is not a valid pattern: unmatched `[`` ``; unknown
rule table → `` unknown rule `no-such-rule` ``. All five carry the
`<config>:<line>:` prefix as specified, exit 2. Stdin (`lucisv check
--stdin-filename … -`) honours the same `[lint.<rule>]` table — confirmed
correct **once run un-guarded**: `tools/guard.sh` backgrounds its command
with `"$@" &`, which severs the child's stdin (confirmed with plain `cat`/
`wc -c` under the guard, piped and redirected both: 0 bytes reach the
child either way) — a guard-wrapped stdin run silently lints an empty
buffer and reports nothing, which is not a `lucisv` bug but is a real trap
for the next QA/dev pass that tries to "always guard" a stdin check. Noting
it here rather than filing as a feature defect: severity LOW, tooling only,
`tools/guard.sh` itself is outside §34's file list. Run un-guarded (single
small file, bounded by hand), the stdin path is correct: `length = 40`
flags, a bad `[lint.line-length] length = "oops"` fails with the same
`<config>:<line>:` message the file path gives.
Editor (`lucisv.lint.options`): no `tests/e2e.rs` case exercises this
setting over a live LSP session — `settings.rs`'s own tests cover
`rule_options()` at the unit level only, so "the editor object over the
wire" in 34.0(f)'s pin list is a unit-level pin, not an e2e one. Verified
it myself with a standalone script speaking framed JSON-RPC at the real
`lucisv-server` binary (same shape as `tests/e2e.rs`'s `talk()`):
`initialize` → `didChangeConfiguration` with `lucisv.lint.options` →
`didOpen`. Five scenarios, all correct: a good `style_regex` fires the
selected rule's diagnostic; a bad key, a wrong-kind value, a bad pattern
and an unknown rule table each produce exactly one `window/logMessage`
warning naming the setting and the reason, are dropped, and the rule keeps
running on its default (never "the linter turned off"). Precedence:
opened a file with a `lucisv.toml` `[lint.line-length] length = 40`
flagging a 58-char line, then pushed `lucisv.lint.options` = `{"line-
length": {"length": 200}}` mid-session — **two publishes**, the second
clearing the diagnostic (editor's 200 beat the toml's 40, and the second
publish is the republish-on-change pin). Recommend landing this script (or
similar) as a checked-in `tests/e2e.rs` case in a follow-up — it is the
only front end 34.0(f) claims a pin for that the repository does not
actually exercise over the wire. Not filed as a severity finding on its
own since the behavior itself is correct; filed as a coverage gap.
**4. 34.1 byte-identity, re-derived independently.** `check --select
enum-name-style,struct-union-name-style,module-name-style,parameter-name-
style --no-config`, this build vs `~/.cache/lucisv-baselines/lucisv-0.36.0`:
corpus **43 findings**, opentitan `hw/` **35 findings**, both stdout and
stderr byte-identical (`diff` empty) in both trees. `git -C
~/repo/opentitan status --porcelain` before and after every opentitan run:
only the three pre-existing modifications (`hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/
ast.sv`) — no CRITICAL.
**5. The 18 rules, adversarial.** No false positive found on a legal shape
in any probe; every probed fix is safe and correct:
- `line-length` correctly ignores a bare `` `include "…140-chars…"` ``, a
bare `` `LONG_MACRO_INVOCATION`` line and the same with a trailing `;`
(still one token); a long string literal *inside* a statement (multiple
tokens on the line) is correctly still reported.
- `posix-eof --fix` appends exactly one `\n` to a file with none; the fix
is idempotent (a second `--fix` run reports nothing).
- `forbid-consecutive-null-statements --fix` collapses `;;` to `;` without
touching the statement around it — semantically inert.
- `generate-label` stayed silent on a hand-crafted file with a genuine
parse error (garbage tokens inside a procedural `if`), confirming the
`parsed_cleanly` gate from the work log's finding 3, while still
flagging an unlabeled `generate … endgenerate` in an otherwise-clean
file.
- `typedef-structs-unions`: a nested anonymous struct is flagged by
default and silenced by `allow_anonymous_nested = true`, both confirmed.
- `always-comb --unsafe-fixes --fix` rewrites `always @(*) begin … end` to
`always_comb begin … end` correctly, is refused under a plain `--fix`
(needs `--unsafe-fixes`, confirmed), matching its documented
Applicability::Unsafe.
- `explicit-begin` confirmed off by default (a non-`begin` `always_comb`
body drew nothing from a plain `lucisv check`) and fires once selected.
- `module-name-style` with a custom `style_regex = "[A-Z][a-zA-Z0-9]*"`
accepts `MyModule` that its own default (lower_snake) would reject —
confirmed both ways.
- `banned-declared-name-patterns` with `patterns = ["[a-z_]+_tmp"]` flags
`foo_tmp` and not `bar` — the option-only rule actually finds something
once configured, not just "0 by construction."
**6. Opentitan census, re-run.** `lucisv check --no-config` over `hw/`,
this build: **4 212 findings total**, exact match. Per-rule counts match
the README's table exactly, including the zero-count rows
(`generate-label-prefix`, `banned-declared-name-patterns`,
`one-module-per-file` off so absent). Five findings read for each of:
- `typedef-structs-unions` — all five in `adc_ctrl_reg_pkg.sv`, all
reggen-generated anonymous nested structs, matching the README's
characterization exactly (true, and the class opentitan's own config
disables).
- `always-comb` — all five in `top_{darjeeling,earlgrey}/ip/ast/rtl/
*_pgd.sv`, all `always @(*)` in the analog behavioural models the README
names as true positives.
- `line-length` — all five in `hw/dv/sv/*`, 101–113 characters, genuine
over-runs, matching the "true, opentitan's own veriblelint sets the same
100-column limit" note.
- `generate-label` — all three (opentitan only has three) in vendored
`lowrisc_ibex`/`pulp_riscv_dbg`, matching exactly.
- `interface-name-style` — all six (opentitan only has six) in vendored
`lowrisc_ibex`/`pulp_riscv_dbg` interfaces (`DMI_BUS_DV`, `JTAG_DV`,
`ibex_mem_intf`, …), matching exactly.
No misclassification found in any of the twenty-five findings read.
Top five rules by count: `typedef-structs-unions` (3 159),
`line-length` (375), `module-port` (161, pre-existing), `instance-
shadowing` (129, pre-existing), `explicit-parameter-storage-type` (88,
pre-existing). Of the twelve new default-on rules, the sum is 3 593,
matching the README's arithmetic exactly.
Recommendation for a lint-clean opentitan, rule by rule, Verible-default
and opentitan's-own-config side by side:
- `typedef-structs-unions` — Verible default **on**; opentitan's own
`hw/lint/tools/veriblelint/lowrisc-styleguide.rules.verible_lint`
disables it outright (`-typedef-structs-unions`). Do not change lucisv's
shipped default (it should still match Verible for every project that
has not opted out) — but this is the one rule I'd flag to the lead as
"opentitan-shaped projects will want `allow_anonymous_nested = true` or
an `ignore`," which the option already delivers; no code change needed,
a documentation callout would help.
- `line-length` — Verible default **on** at 100; opentitan's own config
sets the *same* 100-column limit. No recommendation; the findings are
exactly what opentitan's own tooling would also report.
- `always-comb`, `generate-label`, `interface-name-style` — Verible
default **on** for all three; nothing in opentitan's own veriblelint
config disables any of them, and every finding read is a true positive
in vendored or analog-behavioural code outside the RTL filesets
opentitan lints most strictly. No recommendation to default any of
these off; a project wanting silence there already has `--exclude
vendor/` and `--exclude '*/ast/rtl/*'` available, which is a project
decision, not a shipped-default one.
**7. Docs.** README "Linting" rule table: 54 rows, matches `--rules-doc`'s
54 `## ` sections by name (diffed the two header lists — identical sets).
`docs/site/src/content/docs/reference/rules.md`'s 54 headers diffed
against `--rules-doc`'s — identical. `editors/vscode/README.md` documents
`lucisv.lint.options` with the same precedence note as README.md. TODO §34
checkboxes all ticked except QA, consistent with this file's Status/TODO.
Drift test: in a throwaway worktree (`git worktree add --detach` from
`1d4bddf`, dev's diff applied with `git apply`, untracked files copied,
removed after), added a `FakeDriftRule` to `registry::all_rules()` with no
matching `package.json` entry — `cargo test -p lucisv_server
the_vscode_lint_toggles_match_the_registry` **FAILED** as expected,
naming `fake-drift-rule` in the `right` (registry) side only. Confirms the
drift test is not vacuous. Worktree removed with `git worktree remove
--force`; `git worktree list` afterward shows only the three worktrees
that existed before.
**Verdict: REWORK** — two HIGH findings in `crates/vlog_linter/src/
regex.rs`: (a) `(a*)*b`-shaped user patterns cause exponential
backtracking, reproduced hanging the real `lucisv check` binary until
`tools/guard.sh` killed it (guard kill is itself HIGH per the runaway-guard
rule); (b) unrecognized escape sequences (`\b`, `\1`–`\9`, and any other
dialect escape lucisv's engine does not name) are silently accepted as a
literal character instead of refused, contradicting the feature's own
"refused by name" assumption and producing wrong naming verdicts with no
diagnostic. Everything else verified clean: gates, both option front
ends' validation and precedence (once `tools/guard.sh`'s inability to
forward stdin was worked around — a tooling note, not a product defect),
34.1 byte-identity, the 18 rules' behavior and fixes, the opentitan census
and its arithmetic, the drift test's teeth, and the docs. One coverage gap
noted (LOW): `lucisv.lint.options` "over the wire" has no checked-in
`tests/e2e.rs` case despite 34.0(f)'s pin list, though the behavior itself
is correct by my own live-session probe.
### 2026-09-04 — QA round 2 (Sonnet 5), re-check of the rework
Re-verified the rework that answers round 1's two HIGHs, in the `lint-2`
worktree only, everything guarded, opentitan read-only. Scratch under
`.../scratchpad/qa-34b/`.
**1. Gates, all reproduced independently.** `cargo fmt --all -- --check`
clean. `cargo clippy --all-targets --workspace`: 0 warnings; `git diff
10b63e6` shows no new `#[allow]` anywhere in the whole diff (grepped the
full diff, not just `regex.rs`). `cargo test --workspace --no-fail-fast`:
**3 549 passed / 0 failed / 42 ignored / 48 binaries** — exact match,
counted by summing every `test result:` line, including
`regex::tests::an_ambiguous_repeat_is_linear_not_exponential`,
`an_unsupported_escape_is_refused_by_name` and
`every_probe_agrees_with_python_re_fullmatch` all passing. Corpus gate
(`scripts/score.sh` against the main tree's `corpus/`, read-only, 860
files): `{"passing":814,"total":820,"pct":99.3}`, same five failure
categories. `--stdout` byte-identity over the same 860 files vs
`~/.cache/lucisv-baselines/lucisv-0.36.0`: **0 differ**.
**2. Linearity, adversarially.**
Read `regex.rs` end to end. `Regex::add` (the epsilon-closure walk over
`Split`/`Jump`) marks `seen[pc] = true` **before** recursing into that
state's targets, and returns immediately on a `pc` already marked — so a
cycle of `Split`/`Jump` instructions (exactly the shape `(a*)*` compiles
to: the outer star's `Split`/`Jump` wrapping the inner star's own
`Split`/`Jump`) terminates the moment it revisits a state, rather than
looping. Because `seen` is sized to `self.prog.len()` and reset once per
input character (`on_next` is cleared before each character's closure is
computed, `on_current` fed by the previous character's `on_next` via
`swap`), the total work of one character's closure is bounded by the
program length regardless of how many epsilon paths reach the same
handful of live states — this is the textbook Thompson-NFA/Pike-VM
construction, and the reasoning is airtight: a `pc`'s reachable non-epsilon
successors are a fixed set, so visiting it a second time within the same
character can add nothing `add()` wouldn't already have added the first
time. `is_match`'s outer loop is `O(text)` characters, each doing
`O(prog)` closure and transition work — `O(prog × text)` overall, matching
the doc comment's claim, and no path through `compile`/`emit`/`is_match`
backtracks or holds a continuation.
Timed the **shipped release binary** (not an extracted copy) under
`tools/guard.sh -m 1 -t 10`, for all nine required patterns — `(a*)*b`,
`(a|aa)*b`, `(.*)*x`, `((a*)*)*b`, `(a+)+b`, `(a?)*b`,
`(a*)*(a*)*(a*)*b`, `[a-z]*[a-z]*[a-z]*[a-z]*x`, and a 66-character
overlapping-word alternation
(`(ab|abab|ababab|abababab|ababababab|abababababab|ababababababab)*z`) —
each as a `lucisv.toml` `[lint.signal-name-style] style_regex`, against
wire names of 30/200/1000/5000 `a`-characters (36 runs). Every run
exits 1 (one violation, the pattern correctly not matching an all-`a`
name) with **no guard kill**. Wall time including process spawn and
`guard.sh`'s own overhead was flat at **1.06 s across every combination**
— the guard's one-second poll floor, not lucisv's; re-measured the same
36 runs wrapped in `/usr/bin/time -p` inside the guard to get under that
floor: **every one reports `real 0.00s`** (below `time -p`'s
hundredths-of-a-second resolution) at all four lengths for all nine
patterns, a ×166 growth in name length with no detectable growth in
time. No super-linear growth anywhere — the ladder is flat, not just
sub-second.
**3. Correctness vs Python.**
Extracted all **71** rows of the dev's probe table
(`regex.rs`'s `every_probe_agrees_with_python_re_fullmatch`) with a
character-accurate Rust-string-literal parser (a naive regex-based
extractor first mis-split two rows containing `\n`/`\t` text escapes and
silently dropped them — re-done properly): all 71 checked against
CPython 3's `re.fullmatch`, **71/71 agree**.
Wrote 62 probes of my own (nested groups three deep, alternation inside
`+`/`*`, classes with ranges/negation/`\d\s`-escapes, `.` vs `\n`,
`(a|)`/`(|a)` empty alternatives including nested and repeated ones, `?`
after a group, anchoring including `abc` vs `xabcx`) — all 62 first
verified against CPython, then run against a standalone extraction of
`regex.rs`'s actual `Regex`/`Parser` (source copied out of the crate,
`pub(crate)` widened to `pub`, compiled with plain `rustc` so nothing in
the dev's tree was touched, same technique round 1 used): **62/62 agree
with both Python and lucisv**. One of my first 62 (`"a[\\s\\S]*b"`,
intended as an "any character including newline" idiom) was not a
lucisv bug but a mistake in my own probe: `\S` is a documented refusal
inside a `[...]` class (the negated shorthands need set arithmetic this
engine deliberately doesn't do), so lucisv correctly refused to compile
it; replaced with a valid probe (`[a\n]+`) before counting it in the 62.
20 refusal probes, exactly the list given (`\1 \b \B \A \z \Z \p{L}
\x41 A \0 \e \f \v \h \k<n> \Q \E \G \R \X` — the bare `A` in the middle
is a deliberate control, not an escape): all **19** real escapes were
refused **by name** (`unsupported escape` \`\c\` `, naming the supported
list), and the one control item, the plain literal `A`, correctly
compiled — confirming the refusal is specific to unimplemented escapes
and not over-broad. No silent acceptance of any listed escape.
Confirmed through the CLI on two of them: a `lucisv.toml` with
`[lint.signal-name-style] style_regex = "\bword\b"` (a literal backslash
in the file, not a doubled one — TOML's own `\\` would itself decode to
one backslash before reaching the pattern, which is a config-authoring
detail, not a parser bug) fails `lucisv check` with exactly
```
<config>:2: rule `signal-name-style` `style_regex`: `\bword\b` is not a
valid pattern: unsupported escape `\b` (supported: \d \D \w \W \s \S \n
\t \r, and \<punctuation> for that character)
```
exit 2; and `[lint.constraint-name-style] pattern = "(a)\1"` fails the
same way naming `` `\1` ``. Confirmed through the editor: a standalone
script speaking framed JSON-RPC at the real `lucisv-server` binary (same
technique round 1 used, since no checked-in `tests/e2e.rs` case exists
for `lucisv.lint.options`) pushed `didChangeConfiguration` with
`lucisv.lint.options.signal-name-style.style_regex = "\bword\b"` then
opened a file declaring `IO_CLK`: exactly one `window/logMessage`
warning, `` lucisv: lucisv.lint.options.signal-name-style.style_regex:
`style_regex`: `\bword\b` is not a valid pattern: unsupported escape
`\b` … ; ignored ``, and the rule **kept running on its default**
(`[a-z_0-9]+`) — the diagnostic `signal `IO_CLK` is not lower_snake_case`
still fired. A second push, `lucisv.lint.options.constraint-name-
style.pattern = "(a)\1"`, produced the matching second warning. Neither
push dropped the linter or crashed the session.
**4. Both front ends — item 4's own scenario.** Covered by (3) above:
the CLI refusal names `<config>:<line>:`, the rule and the option; the
editor logs and keeps the default running. No new finding.
**5. Verdict stability.** The 18-rule opentitan census
(`lucisv check --no-config`, read-only, over `~/repo/opentitan/hw`):
**4 212 findings total**, exact match to the README. Full per-rule
breakdown reproduced independently via `--output-format json` and
counted rule-by-rule: every non-zero row matches the README's opentitan
column exactly, including the top five by count
(`typedef-structs-unions` 3 159, `line-length` 375, `module-port` 161,
`instance-shadowing` 129, `explicit-parameter-storage-type` 88) and the
zero/absent rows for every off-by-default rule. `git -C ~/repo/opentitan
status --porcelain` before and after: only the three pre-existing
modifications (`hw/ip/aes/dv/tb/tb.sv`,
`hw/top_darjeeling/ip/ast/rtl/ast.sv`,
`hw/top_earlgrey/ip/ast/rtl/ast.sv`) — read-only held.
The four naming rules (`--select enum-name-style,struct-union-name-
style,module-name-style,parameter-name-style --no-config`), re-derived
against `~/.cache/lucisv-baselines/lucisv-0.36.0`: corpus **43
findings**, opentitan **35 findings**, stdout and stderr byte-identical
in both trees (`diff` empty both ways) — matching the README and round
1's own numbers exactly.
**6. Docs.** `regex.rs`'s `//!` states the supported subset (literals,
`.`, classes with the shorthands, the nine escapes, groups/alternation/
`*+?`, anchors accepted-and-ignored), the refusals (counted repetition,
lookaround, every other escape) and why it cannot hang (Thompson-NFA
simulation, `O(pattern × name)` by construction) — matches the actual
`escape()`/`class_escape()`/`emit_repeat()` code exactly, no drift.
`README.md`'s "Linting" table: 54 rule rows (filtering out the
three-row severity legend that a naive extraction first miscounted as
rule rows) match `lucisv check --rules-doc`'s 54 `## ` sections by name,
identical sets. `docs/site/src/content/docs/reference/rules.md`'s 54
headers diffed against the same list: identical. `editors/vscode/
README.md` documents `lucisv.lint.options` with the same "this setting,
then `lucisv.toml`, then the default" precedence note as `README.md`
line 349. The feature README's Assumptions bullet on the regex subset
and the rework work-log entry both read true against the shipped code.
`TODO.md` §34's checkboxes match this file's Status/TODO (34.0–34.3 and
Gates ticked, QA still open pending this entry).
**No new findings.** Both of round 1's HIGHs are closed: the engine is
structurally linear (Thompson-NFA, verified by reading the closure code
and by a 36-point timing ladder flat from 30 to 5 000 characters across
nine adversarial shapes), and every escape this engine does not
implement is refused by name on both front ends, with the rule falling
back to its default rather than going silent. The LOW coverage gap from
round 1 (no checked-in `tests/e2e.rs` case for `lucisv.lint.options`
over the wire) still stands — worked around again with a throwaway
script, not fixed — and is still the lead's to schedule, not a blocker
for this rework.
**Verdict: PASS.**
## Review
**2026-09-04 — lead.** Accepted after one rework. The option plumbing is
the durable part of this wave: one validator behind both front ends, the
same message with file and line on the CLI and a logged, dropped entry in
the editor, precedence stated once and pinned, `--rules-doc` as the
generated truth. The rework was necessary and the fix is the right kind:
QA showed a user pattern could make every lint run exponential and that
unknown escapes were silently literal; the matcher is now a Thompson-NFA
simulation — linear by construction, proved on nine adversarial shapes
at four name lengths — and unknown escapes are compile errors named
through both doors, with a 71-row table verified against CPython. The
engine swap changed no verdict (the 4 212-finding opentitan census is
identical before and after). One ruling at review, applied here:
`typedef-structs-unions` keeps Verible's default of *on*, but
`allow_anonymous_nested` defaults to **true** — every one of its 3 159
opentitan findings was a nested struct inside a `typedef` in a generated
register package, and opentitan's own Verible config disables the rule
for exactly that; the doc says why and one option restores the stricter
reading. The `generate-label` phantom finding (177 of 180 from
error-recovered UVM files) closed by `parsed_cleanly()` is the kind of
census-driven fix this project exists for. Two LOWs left open and noted:
no checked-in e2e case for `lucisv.lint.options` over the wire (QA drove
it by hand twice), and `always-comb` on plain `.v` files being a judgment
call the unsafe fix and one `ignore` already cover. Ships in 0.38.0;
§35 takes the remaining twenty Verible rules.
+102 -2
View File
@@ -3,18 +3,46 @@ title: Lint rules
description: Complete reference for every lucisv lint rule, its severity, default, fix, and rationale.
---
<span class="badge">36 rules indexed</span>
<span class="badge">54 rules indexed</span>
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.
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 — **and every option a rule takes, with its kind and default**.
A configurable rule is configured in a `[lint.<rule-name>]` table of a `lucisv.toml`, or from an editor in the `lucisv.lint.options` object; the option names are Verible's wherever it has the same option. An unknown rule or option name, a value of the wrong kind, an out-of-range integer or a pattern that does not compile fails a CLI run naming the file and the line, and is ignored (with a log line) in an editor.
```toml
[lint.line-length]
length = 120
[lint.typedef-structs-unions]
allow_anonymous_nested = true
```
A rule marked **on&nbsp;(project)** runs by default only where lucisv can see the other files of your project — `lucisv check <dir>`, 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 | Severity | Default | Fix | Purpose |
|---|:---:|:---:|:---:|---|
| [`always-comb`](#always-comb) | style | on | unsafe | Write `always_comb`, not `always @*` |
| [`banned-declared-name-patterns`](#banned-declared-name-patterns) | style | off | — | Ban the names your project has decided against |
| [`constraint-name-style`](#constraint-name-style) | style | on | — | Name constraints `lower_snake_case` ending `_c` |
| [`explicit-begin`](#explicit-begin) | style | off | safe | Wrap every body in `begin ... end` |
| [`forbid-consecutive-null-statements`](#forbid-consecutive-null-statements) | style | on | safe | Drop a `;` that follows a `;` |
| [`generate-label`](#generate-label) | style | on | — | Label every generate block |
| [`generate-label-prefix`](#generate-label-prefix) | style | on | — | Prefix that label `g_` or `gen_` |
| [`interface-name-style`](#interface-name-style) | style | on | — | Name interfaces `lower_snake_case` ending `_if` |
| [`line-length`](#line-length) | style | on | — | Keep lines within the configured width |
| [`macro-name-style`](#macro-name-style) | style | on | — | Name macros `ALL_CAPS` |
| [`one-module-per-file`](#one-module-per-file) | style | off | — | Declare one module per file |
| [`package-filename`](#package-filename) | style | on | — | Match one-package files to package names |
| [`parameter-type-name-style`](#parameter-type-name-style) | style | off | — | Name `type` parameters `lower_snake_case` ending `_t` |
| [`port-name-suffix`](#port-name-suffix) | style | off | — | Say a port's direction in its name |
| [`posix-eof`](#posix-eof) | style | on | safe | End the file with a newline |
| [`signal-name-style`](#signal-name-style) | style | off | — | Name signals `lower_snake_case` |
| [`typedef-enums`](#typedef-enums) | style | on | — | Name an `enum` type with a `typedef` |
| [`typedef-structs-unions`](#typedef-structs-unions) | style | on | — | Name a `struct`/`union` type with a `typedef` |
| [`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 |
@@ -195,3 +223,75 @@ Reports a `.name(…)` connection naming a port the instantiated module does not
## 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.
## always-comb
Reports `always @*` and `always @(*)`, which SystemVerilog spells `always_comb`. The keyword is checked by the tool — a second driver of the block's outputs becomes an error, and the inferred sensitivity list reaches into the functions the block calls. Verible enables its rule of the same name by default. The fix is offered but **unsafe**: `always_comb` runs once at time zero and `always @*` does not, so a testbench that samples before the first change can see a different value.
## banned-declared-name-patterns
Reports a declared name matching one of the patterns in the `patterns` option, which is empty by default — the rule is a place for a project to point at its own list (a deprecated prefix, a vendor's namespace, the `tmp` a review keeps catching). Every declared name is judged: modules, packages, types, parameters, signals, ports, instances, labels. A pattern must match the whole name.
## constraint-name-style
Reports a `constraint` whose name does not match `([a-z0-9]+_)+c` (the `pattern` option) — the shape Verible enables by default. A constraint's name is what a test turns off with `constraint_mode(0)`, so it is read far from its declaration.
## explicit-begin
Reports a body that is a single statement rather than a `begin ... end` block, for eleven constructs each with its own `*_enable` option (`if_enable`, `else_enable`, `always_ff_enable`, …), all on when the rule is. Off by default here as in Verible: the style is far from universal, and a codebase that did not start with it cannot adopt it one line at a time. An `else if` chain is never reported. The safe fix wraps the body; run the formatter afterwards to lay it out.
## forbid-consecutive-null-statements
Reports a null statement whose preceding token is a `;` — the `;;` an edit leaves behind, and the statement twin of `empty-item`. The empty header of `for (;;)` is not a statement and is never reported. The safe fix deletes the extra `;`.
## generate-label
Reports a generate `begin` with no `: label`. An unlabelled block still gets a name (`genblk3`), and that invented name is what appears in every hierarchical path — and it renumbers the moment a block is added above it. Silent in a file that does not fully parse: error recovery can rebind a procedural `begin` as a generate one, which on opentitan accounted for 177 of 180 findings before the guard was added.
## generate-label-prefix
Reports a generate label that starts with none of the `prefix` option's entries, `g_` and `gen_` by default. The prefix is what makes the generate levels of a hierarchical path visible. An empty list accepts every label while `generate-label` still requires there to be one.
## interface-name-style
Reports an `interface` whose name does not match `[a-z_0-9]+(_if)` (the `style_regex` option) — Verible's default pattern. Nothing in the syntax says an identifier is an interface rather than a module or a class; the suffix does.
## line-length
Reports a line wider than the limit — by default **the width the formatter is configured with for that file**, so the two halves of lucisv cannot disagree; the `length` option overrides it. The check is token-aware, as Verible's is: a line holding one unbreakable token (a long string, an `` `include`` path, a macro invocation) is left alone, because no wrapping could shorten it. There is no fix — where to break a line is what the formatter is for.
## macro-name-style
Reports a `` `define`` whose name does not match `[A-Z_0-9]+` (the `style_regex` option). A macro obeys no scope and can rewrite the code around its use, which is why every language that has them marks them by case. Only the definition is judged, never the uses.
## one-module-per-file
Reports every `module` after the first in a file. Off by default, as in Verible: plenty of real RTL keeps small helper modules beside the one the file is named for. An `interface`, a `program` and a `package` are not modules. Silent in a file that does not fully parse, where recovery can promote a nested declaration to file scope.
## package-filename
Reports a one-package file whose name matches neither the package (`foo.sv`) nor the package with a `_pkg` suffix (`foo_pkg.sv`), the two spellings the industry writes. The `allow-dash-for-underscore` option accepts `foo-pkg.sv` as well. Silent for stdin and for a file that does not fully parse; renaming a file is not the linter's business, so there is no fix.
## parameter-type-name-style
Reports a `type` parameter whose name does not match `[a-z][a-z_0-9]*_t` (the `style_regex` option). A type parameter is a type, and naming it `T` makes a declaration read like an expression. Off by default here as in Verible: `#(type T = int)` is near-universal in UVM code.
## port-name-suffix
Reports a port whose name does not end in the suffix for its direction — `_i`/`_ni` for an input, `_o`/`_no` for an output, `_io`/`_nio` for an `inout`, where the `n` marks active-low. The `suffixes` option is the accepted list; one of the six known suffixes is accepted only for its own direction, and anything else a project adds is accepted for any. Off by default: a codebase cannot adopt the convention one port at a time.
## posix-eof
Reports a file whose last line has no newline — formally, a file with no last line: `wc -l` counts short, and the next edit's diff shows the final line twice. The safe fix appends the newline. An empty file is left alone.
## signal-name-style
Reports a net, variable or port inside a module, interface or program whose name does not match `[a-z_0-9]+` (the `style_regex` option). Off by default here as in Verible: switching it on for an existing codebase reports thousands of findings on the first run, which is a project's decision. Class properties, `parameter`s and subroutine locals are other rules' business, or nobody's.
## typedef-enums
Reports a declaration whose type is an anonymous `enum`. The language gives no way to name such a type afterwards: a function cannot take it, a port cannot carry it, and two variables declared with the same member list are different types to the compiler.
## typedef-structs-unions
Reports a declaration whose type is an anonymous `struct` or `union`, for the reasons `typedef-enums` gives. The `allow_anonymous_nested` option (true by default here — Verible defaults it to false) exempts an aggregate written inside another aggregate's body — which is what auto-generated register packages are made of: on opentitan `hw/`, all 3 159 findings are nested structs inside a `typedef` in 57 `reggen`-generated files, and opentitan's own Verible config disables the rule with the comment "we allow nested struct definitions". One option, or one `ignore`, expresses the same choice here.
+20
View File
@@ -287,6 +287,7 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
| `lucisv.lint.rules.<rule>` | `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.lint.options` | `{}` | Per-rule options, as `{ "<rule>": { "<option>": value } }` — the editor's spelling of a `[lint.<rule>]` table in `lucisv.toml`. Each rule's own dropdown names the options it takes, and `lucisv check --rules-doc` prints every one with its kind and default. A bad entry is ignored and reported in the lucisv output channel, so one typo cannot switch the linter off |
| `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 |
@@ -305,6 +306,25 @@ above it:
4. a per-rule dropdown set to `on` or `off` decides that one rule;
5. `lucisv.lint.ignore` removes, whatever anything else said.
`lucisv.lint.options` is not part of that ladder — it does not choose *which*
rules run, it configures the ones that do:
```json
"lucisv.lint.options": {
"line-length": { "length": 120 },
"typedef-structs-unions": { "allow_anonymous_nested": true },
"generate-label-prefix": { "prefix": ["g_", "gen_"] }
}
```
For an option, the precedence is **this setting, then the `lucisv.toml`, then
the rule's own default — key by key**, so a project can set two options and you
can override a third without losing the others. That is deliberately the
opposite order to the style settings below: formatting has a byte-exact
contract with CI that your editor must not break, while which findings *you*
are shown is yours to choose. Changing an option re-checks every open file
immediately, exactly as a toggle does.
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
contain projects with different formatting rules.
+237 -14
View File
@@ -349,6 +349,13 @@
"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.options": {
"type": "object",
"default": {},
"order": 13,
"additionalProperties": true,
"markdownDescription": "Per-rule lint options, as `{ \"<rule-name>\": { \"<option>\": value } }` — the editor's spelling of a `[lint.<rule-name>]` table in `lucisv.toml`. Example: `{ \"line-length\": { \"length\": 120 }, \"generate-label-prefix\": { \"prefix\": [\"g_\", \"gen_\"] } }`. Each rule's own toggle below names the options it takes, and `lucisv check --rules-doc` prints every option with its kind and default. An entry naming a rule or an option that does not exist — or carrying a value of the wrong kind, an integer out of range or a pattern that does not compile — is ignored and reported in the lucisv log, so one typo cannot switch the linter off. A rule option set here beats the same option in a `lucisv.toml`, key by key. Takes effect immediately — every open file is re-checked."
},
"lucisv.lint.severity.error": {
"type": "boolean",
"default": true,
@@ -679,7 +686,7 @@
"order": 45,
"markdownDescription": "**warning** — cast to `void` only what a call returns. On by default."
},
"lucisv.lint.rules.empty-item": {
"lucisv.lint.rules.always-comb": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
@@ -689,6 +696,42 @@
],
"default": "default",
"order": 46,
"markdownDescription": "**style** — write `always_comb` instead of `always @*`. On by default."
},
"lucisv.lint.rules.banned-declared-name-patterns": {
"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": 47,
"markdownDescription": "**style** — do not declare a name the project has banned. Off by default. Options (set them in `#lucisv.lint.options#`): `patterns`."
},
"lucisv.lint.rules.constraint-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": 48,
"markdownDescription": "**style** — name constraints in lower_snake_case ending in _c. On by default. Options (set them in `#lucisv.lint.options#`): `pattern`."
},
"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": 49,
"markdownDescription": "**style** — drop a `;` that stands where an item belongs. On by default."
},
"lucisv.lint.rules.enum-name-style": {
@@ -700,8 +743,20 @@
"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."
"order": 50,
"markdownDescription": "**style** — name enum typedefs in lower_snake_case ending in _e or _t. On by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
},
"lucisv.lint.rules.explicit-begin": {
"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": 51,
"markdownDescription": "**style** — wrap every body in `begin` and `end`. Off by default. Options (set them in `#lucisv.lint.options#`): `always_comb_enable`, `always_enable`, `always_ff_enable`, `always_latch_enable`, `else_enable`, `final_enable`, `for_enable`, `forever_enable`, `if_enable`, `initial_enable`, `while_enable`."
},
"lucisv.lint.rules.explicit-parameter-storage-type": {
"type": "string",
@@ -712,9 +767,81 @@
"Never run this rule."
],
"default": "default",
"order": 48,
"order": 52,
"markdownDescription": "**style** — declare a storage type on every parameter. On by default."
},
"lucisv.lint.rules.forbid-consecutive-null-statements": {
"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** — remove the extra `;`. On by default."
},
"lucisv.lint.rules.generate-label": {
"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** — label every generate block. On by default."
},
"lucisv.lint.rules.generate-label-prefix": {
"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** — prefix a generate block's label with `g_` or `gen_`. On by default. Options (set them in `#lucisv.lint.options#`): `prefix`."
},
"lucisv.lint.rules.interface-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": 56,
"markdownDescription": "**style** — name interfaces in lower_snake_case ending in _if. On by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
},
"lucisv.lint.rules.line-length": {
"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": 57,
"markdownDescription": "**style** — keep lines within the configured width. On by default. Options (set them in `#lucisv.lint.options#`): `length`."
},
"lucisv.lint.rules.macro-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": 58,
"markdownDescription": "**style** — name macros in ALL_CAPS. On by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
},
"lucisv.lint.rules.module-filename": {
"type": "string",
"enum": ["default", "on", "off"],
@@ -724,7 +851,7 @@
"Never run this rule."
],
"default": "default",
"order": 49,
"order": 59,
"markdownDescription": "**style** — name a one-module file after its module. On by default."
},
"lucisv.lint.rules.module-name-style": {
@@ -736,8 +863,8 @@
"Never run this rule."
],
"default": "default",
"order": 50,
"markdownDescription": "**style** — name modules in lower_snake_case. Off by default."
"order": 60,
"markdownDescription": "**style** — name modules in lower_snake_case. Off by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
},
"lucisv.lint.rules.no-tabs": {
"type": "string",
@@ -748,7 +875,7 @@
"Never run this rule."
],
"default": "default",
"order": 51,
"order": 61,
"markdownDescription": "**style** — use spaces, not tabs. On by default."
},
"lucisv.lint.rules.no-trailing-whitespace": {
@@ -760,9 +887,33 @@
"Never run this rule."
],
"default": "default",
"order": 52,
"order": 62,
"markdownDescription": "**style** — no whitespace at the end of a line. On by default."
},
"lucisv.lint.rules.one-module-per-file": {
"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": 63,
"markdownDescription": "**style** — declare one module per file. Off by default."
},
"lucisv.lint.rules.package-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": 64,
"markdownDescription": "**style** — name a one-package file after its package. On by default. Options (set them in `#lucisv.lint.options#`): `allow-dash-for-underscore`."
},
"lucisv.lint.rules.parameter-name-style": {
"type": "string",
"enum": ["default", "on", "off"],
@@ -772,8 +923,56 @@
"Never run this rule."
],
"default": "default",
"order": 53,
"markdownDescription": "**style** — name parameters in CamelCase or ALL_CAPS. On by default."
"order": 65,
"markdownDescription": "**style** — name parameters in CamelCase or ALL_CAPS. On by default. Options (set them in `#lucisv.lint.options#`): `localparam_style`, `localparam_style_regex`, `parameter_style`, `parameter_style_regex`."
},
"lucisv.lint.rules.parameter-type-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": 66,
"markdownDescription": "**style** — name type parameters in lower_snake_case ending in _t. Off by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
},
"lucisv.lint.rules.port-name-suffix": {
"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": 67,
"markdownDescription": "**style** — end a port's name with the suffix for its direction. Off by default. Options (set them in `#lucisv.lint.options#`): `suffixes`."
},
"lucisv.lint.rules.posix-eof": {
"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": 68,
"markdownDescription": "**style** — end the file with a newline. On by default."
},
"lucisv.lint.rules.signal-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": 69,
"markdownDescription": "**style** — name signals in lower_snake_case. Off by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
},
"lucisv.lint.rules.struct-union-name-style": {
"type": "string",
@@ -784,8 +983,32 @@
"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."
"order": 70,
"markdownDescription": "**style** — name struct and union typedefs in lower_snake_case ending in _t. On by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
},
"lucisv.lint.rules.typedef-enums": {
"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": 71,
"markdownDescription": "**style** — give an enum type a name with `typedef`. On by default."
},
"lucisv.lint.rules.typedef-structs-unions": {
"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": 72,
"markdownDescription": "**style** — give a struct or union type a name with `typedef`. On by default. Options (set them in `#lucisv.lint.options#`): `allow_anonymous_nested`."
},
"lucisv.lint.rules.unused-waiver": {
"type": "string",
@@ -796,7 +1019,7 @@
"Never run this rule."
],
"default": "default",
"order": 55,
"order": 73,
"markdownDescription": "**style** — remove waivers that no longer suppress anything. On by default."
}
}