diff --git a/README.md b/README.md index 167fe24..5322095 100644 --- a/README.md +++ b/README.md @@ -242,6 +242,11 @@ makes an editor's red squiggle worth believing. | `instance-shadowing` | warning | — | no declaration hides an enclosing one | | `undriven-net` † | warning | — | everything read is driven by something | | `unused-signal` † | warning | — | no net or variable nothing uses | +| `create-object-name-match` | warning | — | `type_id::create("x")` names the handle `x` | +| `forbidden-macro` | warning | — | no macro on the project's forbidden list | +| `uvm-macro-semicolon` | warning | — | no `;` after a `` `uvm_* `` macro (off by default) | +| `macro-string-concatenation` | warning | — | no `` `` `` inside a plain string (off by default) | +| `disable-statement` | warning | — | `disable fork`, not a fork label (off by default) | | `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) | | `no-trailing-whitespace` | style | safe | nothing but code before the newline | | `empty-item` | style | safe | no `;` standing where an item belongs | @@ -270,6 +275,20 @@ makes an editor's red squiggle worth believing. | `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 | +| `explicit-function-lifetime` | style | — | `automatic`/`static` on a function outside a class | +| `explicit-task-lifetime` | style | — | `automatic`/`static` on a task outside a class | +| `positive-meaning-parameter-name` | style | — | no `disable`-prefixed parameter name | +| `suggest-parentheses` | style | safe | `a ? (b ? c : d) : e`, parenthesized | +| `unpacked-dimensions-range-ordering` | style | — | an unpacked dimension is `[0:N-1]` | +| `module-begin-block` | style | — | no `begin`/`end` at module scope | +| `v2001-generate-begin` | style | — | no bare `begin` in a generate region | +| `forbid-line-continuations` | style | — | no `\` breaking a string literal | +| `legacy-generate-region` | style | — | no `generate … endgenerate` wrapper (off) | +| `legacy-genvar-declaration` | style | — | a genvar is declared in the `for` header (off) | +| `endif-comment` | style | safe | `` `endif `` names what it closes (off by default) | +| `numeric-format-string-style` | style | — | a radix prefix matches its specifier (off) | +| `proper-parameter-declaration` | style | — | `parameter` in a header, `localparam` in a body (off) | +| `dff-name-style` | style | — | a flip-flop is `_q`, its input `_d` (off by default) | † On by default when lucisv can see a project (a multi-file CLI run or the language server), and off for a single file or stdin unless `--select` names diff --git a/TODO.md b/TODO.md index 42c2954..6d92288 100644 --- a/TODO.md +++ b/TODO.md @@ -3830,12 +3830,12 @@ Rules (Verible default → lucisv default; severity; options): Plus the LOW from §34's QA: a checked-in `tests/e2e.rs` case for `lucisv.lint.options` over the wire. Docs: the toggles regenerated, README.md rows, docs-site sections, coverage_gaps "linter" addendum. -- [ ] the twenty rules, each with tests and counts -- [ ] `void-cast` option; `forbidden-*` lists; `invalid-system-task- +- [x] the twenty rules, each with tests and counts +- [x] `void-cast` option; `forbidden-*` lists; `invalid-system-task- function` reconciled -- [ ] e2e case for `lucisv.lint.options` -- [ ] docs + regenerated toggles -- [ ] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus +- [x] e2e case for `lucisv.lint.options` +- [x] docs + regenerated toggles +- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus 814/820 byte-identical; vsix smoke; opentitan census + timing - [ ] QA: every rule attacked; census re-read; options attacked diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 531d319..2fb946f 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -7367,6 +7367,81 @@ fn the_project_wide_lint_rules_publish_and_a_setting_turns_them_off() { let _ = std::fs::remove_dir_all(&dir); } +/// `lucisv.lint.options` over the wire — the pin §34's QA found missing and +/// drove by hand twice (`docs/features/linter-expansion-2/README.md`, QA log). +/// +/// Three claims a unit test cannot make: the object survives +/// `didChangeConfiguration` and changes what is published; the editor's value +/// beats a checked-in `lucisv.toml`'s, key by key; and a refused entry is +/// *dropped and logged* rather than fatal — the rule keeps running, here on +/// the `lucisv.toml` value the bad entry failed to override. +#[test] +fn the_lint_options_setting_changes_what_is_published_and_a_bad_entry_is_logged() { + let dir = temp_dir("lintoptions"); + std::fs::write(dir.join("lucisv.toml"), "[lint.line-length]\nlength = 40\n").expect("write"); + let file = dir.join("wide.sv"); + let text = "module wide;\n wire this_line_is_a_good_deal_wider_than_forty;\nendmodule\n"; + std::fs::write(&file, text).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(text).expect("json") + )), + // The editor's value beats the checked-in one, key by key. + frame( + r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"lint":{"options":{"line-length":{"length":200}}}}}}}"#, + ), + // ... and a typo'd key is refused, dropped and logged, leaving the + // `lucisv.toml` value standing rather than turning the linter off. + frame( + r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"lint":{"options":{"line-length":{"lenght":200}}}}}}}"#, + ), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let wide: Vec = messages + .iter() + .filter(|m| m["method"] == "textDocument/publishDiagnostics") + .filter(|m| m["params"]["uri"] == uri.as_str()) + .map(|m| { + m["params"]["diagnostics"] + .as_array() + .map(|list| list.iter().filter(|d| d["code"] == "line-length").count()) + .unwrap_or(0) + }) + .collect(); + assert!(wide.len() >= 3, "one publish per state: {wide:?}"); + assert_eq!(wide[0], 1, "the `lucisv.toml`'s 40 flags the 47-column line: {wide:?}"); + assert_eq!(wide[1], 0, "the editor's 200 beat it: {wide:?}"); + assert_eq!( + wide[wide.len() - 1], + 1, + "the refused entry is dropped, so the `lucisv.toml` value stands again: {wide:?}" + ); + + let logged: Vec<&str> = messages + .iter() + .filter(|m| m["method"] == "window/logMessage") + .filter_map(|m| m["params"]["message"].as_str()) + .filter(|text| text.contains("lucisv.lint.options")) + .collect(); + assert_eq!(logged.len(), 1, "exactly the one refused entry: {logged:?}"); + assert!(logged[0].contains("lenght"), "{}", logged[0]); + assert!(logged[0].contains("ignored"), "{}", logged[0]); + + let _ = std::fs::remove_dir_all(&dir); +} + /// `lucisv.instantiate` — `docs/topo.md` §2.9-19. What only an e2e test can /// check: that the command is advertised in `initialize`, that its three /// arguments survive the wire, and that the skeleton arrives as a diff --git a/crates/vlog_linter/src/exprs.rs b/crates/vlog_linter/src/exprs.rs new file mode 100644 index 0000000..dae869d --- /dev/null +++ b/crates/vlog_linter/src/exprs.rs @@ -0,0 +1,306 @@ +//! Every expression written in a file. +//! +//! `visit` walks the item and statement spines and `decls` the types and +//! dimensions; neither reaches *into* an expression, and a rule that judges +//! the shape of one (`suggest-parentheses`) needs every node of every tree, +//! wherever it was written. Collecting them lives here so each of the three +//! files stays one sentence long. + +use vlog_parser::ast::{ + Connections, Expr, ExprKind, ForStep, Instantiation, ItemKind, ListElem, SourceFile, StmtKind, + TimingControl, +}; + +use crate::visit::{walk_all_stmts, walk_items, walk_param_ports}; + +/// Calls `f` on every expression of the file, sub-expressions included. +/// +/// The **roots** are the places an expression is written: a continuous or +/// procedural assignment, a declaration's initialiser, a condition, a call +/// argument, an instantiation's connections, a generate header, an expression +/// statement. Sub-expressions are then reached through every composite +/// [`ExprKind`], so a node buried in a concatenation inside a call argument is +/// visited like any other. +pub(crate) fn walk_exprs(file: &SourceFile, f: &mut dyn FnMut(&Expr)) { + let mut root = |expr: &Expr| descend(expr, f); + walk_param_ports(file, &mut |port| { + if let Some(default) = &port.default { + root(default); + } + }); + walk_items(file, &mut |item| match &item.kind { + ItemKind::ContAssign(assign) => { + if let Some(delay) = &assign.delay { + root(delay); + } + for pair in &assign.assigns { + root(&pair.lhs); + root(&pair.rhs); + } + } + ItemKind::ParamDecl(decl) => initialisers(&decl.declarators, &mut root), + ItemKind::DataDecl(decl) => initialisers(&decl.declarators, &mut root), + ItemKind::PortDecl(decl) => initialisers(&decl.declarators, &mut root), + ItemKind::ElabTask(expr) => root(expr), + ItemKind::Instantiation(inst) => connections(inst, &mut root), + ItemKind::Bind(bind) => connections(&bind.inst, &mut root), + ItemKind::GenIf(gen_if) => root(&gen_if.cond), + ItemKind::GenFor(gen_for) => { + root(&gen_for.init.lhs); + root(&gen_for.init.rhs); + root(&gen_for.cond); + match &gen_for.step { + ForStep::Assign(assign) => { + root(&assign.lhs); + root(&assign.rhs); + } + ForStep::Expr(expr) => root(expr), + } + } + ItemKind::GenCase(gen_case) => { + root(&gen_case.expr); + for case_item in &gen_case.items { + for label in &case_item.labels { + root(&label.expr); + } + } + } + ItemKind::Defparam(pairs) => { + for (target, value) in pairs { + root(target); + root(value); + } + } + ItemKind::Alias(terms) => { + for term in terms { + root(term); + } + } + _ => {} + }); + walk_all_stmts(file, &mut |stmt| match &stmt.kind { + StmtKind::Assign { lhs, rhs, timing, .. } => { + root(lhs); + root(rhs); + if let Some(TimingControl::Delay { expr, .. }) = timing { + root(expr); + } + } + StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => root(expr), + StmtKind::If { cond, .. } => root(cond), + StmtKind::Case { expr, items, .. } => { + root(expr); + for case_item in items { + for label in &case_item.labels { + root(&label.expr); + } + } + } + StmtKind::RandCase { items, .. } => { + for case_item in items { + for label in &case_item.labels { + root(&label.expr); + } + } + } + StmtKind::For { init, cond, step, .. } => { + for one in init { + root(&one.assign.lhs); + root(&one.assign.rhs); + } + if let Some(cond) = cond { + root(cond); + } + for one in step { + match one { + ForStep::Assign(assign) => { + root(&assign.lhs); + root(&assign.rhs); + } + ForStep::Expr(expr) => root(expr), + } + } + } + StmtKind::While { cond, .. } | StmtKind::DoWhile { cond, .. } => root(cond), + StmtKind::Repeat { count, .. } => root(count), + StmtKind::Foreach { target, .. } => root(target), + StmtKind::Wait { cond, .. } => root(cond), + // A sensitivity list holds edge terms, not values; only the `#delay` + // spelling carries an expression a rule would judge. + StmtKind::Timing { control: TimingControl::Delay { expr, .. }, .. } => root(expr), + StmtKind::ForceRelease { lhs, rhs, .. } => { + root(lhs); + if let Some(rhs) = rhs { + root(rhs); + } + } + StmtKind::Return { expr: Some(expr), .. } => root(expr), + StmtKind::VarDecl(decl) => initialisers(&decl.declarators, &mut root), + StmtKind::ParamDecl(decl) => initialisers(&decl.declarators, &mut root), + StmtKind::PortDecl(decl) => initialisers(&decl.declarators, &mut root), + _ => {} + }); +} + +fn initialisers(declarators: &[vlog_parser::ast::Declarator], root: &mut dyn FnMut(&Expr)) { + for declarator in declarators { + if let Some(init) = &declarator.init { + root(init); + } + } +} + +fn connections(inst: &Instantiation, root: &mut dyn FnMut(&Expr)) { + if let Some(params) = &inst.params { + for conn in params.iter().filter_map(ListElem::ok) { + if let Some(expr) = &conn.expr { + root(expr); + } + } + } + for instance in &inst.instances { + match &instance.conns { + Connections::Named(conns) => { + for conn in conns.iter().filter_map(ListElem::ok) { + if let Some(expr) = &conn.expr { + root(expr); + } + } + } + Connections::Ordered(conns) => { + for conn in conns.iter().filter_map(ListElem::ok) { + if let Some(expr) = &conn.expr { + root(expr); + } + } + } + } + } +} + +/// One expression and everything inside it. +fn descend(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + match &expr.kind { + ExprKind::Unary { expr: inner, .. } + | ExprKind::Postfix { expr: inner, .. } + | ExprKind::New(inner) + | ExprKind::Paren { inner, .. } => descend(inner, f), + ExprKind::Binary { lhs, rhs, .. } => { + descend(lhs, f); + descend(rhs, f); + } + ExprKind::Ternary { cond, then, els, .. } => { + descend(cond, f); + descend(then, f); + descend(els, f); + } + ExprKind::Call { callee, args, .. } => { + descend(callee, f); + for arg in args { + descend(&arg.expr, f); + } + } + ExprKind::Index { base, index, .. } => { + descend(base, f); + descend(index, f); + } + ExprKind::Range { base, msb, lsb, .. } => { + descend(base, f); + descend(msb, f); + descend(lsb, f); + } + ExprKind::Member { base, .. } + | ExprKind::Scope { base, .. } + | ExprKind::Parameterized { base, .. } => descend(base, f), + ExprKind::Concat(items) => { + for item in items { + descend(&item.expr, f); + } + } + ExprKind::Repl { count, inner } | ExprKind::AssignPatternRepl { count, inner } => { + descend(count, f); + for item in inner { + descend(&item.expr, f); + } + } + ExprKind::Stream { slice, inner, .. } => { + if let Some(slice) = slice { + descend(slice, f); + } + for item in inner { + descend(&item.expr, f); + } + } + ExprKind::Cast { ty, expr: inner, .. } => { + descend(ty, f); + descend(inner, f); + } + ExprKind::Inside { lhs, ranges, .. } => { + descend(lhs, f); + for item in ranges { + descend(&item.expr, f); + } + } + ExprKind::InsideMacro { lhs, .. } => descend(lhs, f), + ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => descend(base, f), + ExprKind::Dist { expr: inner, .. } => descend(inner, f), + ExprKind::NamedArg { value, .. } => descend(value, f), + ExprKind::AssignPattern(items) => { + for item in items { + if let Some(key) = &item.key { + descend(key, f); + } + descend(&item.value, f); + } + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vlog_parser::parse_source_tolerant; + + fn ternaries(src: &str) -> usize { + let (file, _) = parse_source_tolerant(src); + let mut n = 0; + walk_exprs(&file, &mut |expr| { + if matches!(expr.kind, ExprKind::Ternary { .. }) { + n += 1; + } + }); + n + } + + #[test] + fn reaches_an_expression_written_anywhere() { + let src = "module m #(parameter int P = a ? 1 : 2) (\n\ + input logic i\n\ + );\n\ + logic v = b ? 1 : 2;\n\ + assign w = c ? 1 : 2;\n\ + sub u (.p(d ? 1 : 2));\n\ + if (e ? 1 : 2) begin : g\n wire x;\n end\n\ + initial begin\n\ + if (f ? 1 : 2) y = g_ ? 1 : 2;\n\ + z = {h ? 1 : 2, call(i ? 1 : 2)};\n\ + end\n\ + endmodule\n"; + assert_eq!(ternaries(src), 9); + } + + #[test] + fn a_nested_expression_is_reached_through_every_composite() { + assert_eq!(ternaries("module m;\n assign x = ~(a ? 1 : 2);\nendmodule\n"), 1); + assert_eq!(ternaries("module m;\n assign x = y[a ? 1 : 2];\nendmodule\n"), 1); + assert_eq!(ternaries("module m;\n assign x = int'(a ? 1 : 2);\nendmodule\n"), 1); + assert_eq!(ternaries("module m;\n assign x = {2{a ? 1 : 2}};\nendmodule\n"), 1); + } + + #[test] + fn a_file_with_no_expressions_visits_nothing() { + assert_eq!(ternaries("module m;\nendmodule\n"), 0); + } +} diff --git a/crates/vlog_linter/src/lib.rs b/crates/vlog_linter/src/lib.rs index a3a54f2..64fbd74 100644 --- a/crates/vlog_linter/src/lib.rs +++ b/crates/vlog_linter/src/lib.rs @@ -22,11 +22,13 @@ mod context; mod decls; +mod exprs; mod interfaces; mod literal; mod module_decls; mod naming; mod options; +mod preproc; mod regex; mod registry; mod rule_docs; @@ -201,12 +203,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 explicit-function-lifetime\n wire a;\nendmodule\n"; + let src = "module m;\n // verilog_lint: waive forbid-implicit-declarations\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 explicit-function-lifetime\n wire a;\nendmodule\n"; + "module m;\n // lucisv: waive forbid-implicit-declarations\n wire a;\nendmodule\n"; assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]); } diff --git a/crates/vlog_linter/src/preproc.rs b/crates/vlog_linter/src/preproc.rs new file mode 100644 index 0000000..ff24fff --- /dev/null +++ b/crates/vlog_linter/src/preproc.rs @@ -0,0 +1,105 @@ +//! What a preprocessor token says: the name a macro invocation calls, and the +//! word and operand a compiler directive carries. +//! +//! The lexer keeps both shapes as single tokens — a macro invocation +//! (`` `uvm_info("A", "B", UVM_LOW) ``) is one `Ident` whose text starts with +//! a backtick and swallows its balanced arguments, and a directive +//! (`` `ifdef FOO ``) is one `Directive` running to the end of its (possibly +//! continued) line. Four rules read those texts; reading them in one place is +//! what stops the four from disagreeing about where a name starts and ends. + +use vlog_parser::token::{Token, TokenKind}; + +/// The macro this token invokes, without its backtick or arguments, or `None` +/// for a token that is not a macro invocation. +pub(crate) fn macro_name(token: &Token) -> Option<&str> { + if token.kind != TokenKind::Ident { + return None; + } + let rest = token.text.strip_prefix('`')?; + let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len()); + match end { + 0 => None, + _ => Some(&rest[..end]), + } +} + +/// The keyword of a compiler directive (`ifdef`, `endif`, `define`), or `None` +/// for a token that is not one. +pub(crate) fn directive_word(token: &Token) -> Option<&str> { + if token.kind != TokenKind::Directive { + return None; + } + let rest = token.text.strip_prefix('`')?; + let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len()); + match end { + 0 => None, + _ => Some(&rest[..end]), + } +} + +/// The name a directive names — the `FOO` of `` `ifdef FOO `` — or `None` when +/// it names nothing. +pub(crate) fn directive_operand(token: &Token) -> Option<&str> { + let word = directive_word(token)?; + let rest = token.text.get(1 + word.len()..)?.trim_start(); + let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len()); + match end { + 0 => None, + _ => Some(&rest[..end]), + } +} + +/// The characters an identifier is made of, matching the lexer's own rule. +fn is_name_char(c: char) -> bool { + c == '_' || c == '$' || c.is_ascii_alphanumeric() +} + +#[cfg(test)] +mod tests { + use super::*; + use vlog_parser::tokenize; + + fn tokens(src: &str) -> Vec { + tokenize(src).expect("lexes") + } + + #[test] + fn a_macro_invocation_gives_its_name() { + let toks = tokens("module m;\n initial `uvm_info(\"A\", \"B\", UVM_LOW);\nendmodule\n"); + let names: Vec<&str> = toks.iter().filter_map(macro_name).collect(); + assert_eq!(names, vec!["uvm_info"]); + } + + #[test] + fn a_macro_without_arguments_gives_its_name_too() { + let toks = tokens("module m;\n `ASSERT_INIT\nendmodule\n"); + assert_eq!(toks.iter().filter_map(macro_name).collect::>(), vec!["ASSERT_INIT"]); + } + + #[test] + fn an_ordinary_identifier_is_not_a_macro() { + let toks = tokens("module m;\n wire uvm_info;\nendmodule\n"); + assert!(toks.iter().filter_map(macro_name).next().is_none()); + } + + #[test] + fn a_directive_gives_its_word_and_operand() { + let toks = tokens("`ifdef FOO\n`endif\n`define BAR 1\nmodule m;\nendmodule\n"); + let words: Vec<&str> = toks.iter().filter_map(directive_word).collect(); + assert_eq!(words, vec!["ifdef", "endif", "define"]); + let operands: Vec> = + toks.iter().filter(|t| t.kind == TokenKind::Directive).map(directive_operand).collect(); + assert_eq!(operands, vec![Some("FOO"), None, Some("BAR")]); + } + + #[test] + fn a_directive_is_not_a_macro_invocation_and_the_other_way_round() { + let toks = tokens("`ifdef FOO\nmodule m;\n `ASSERT\nendmodule\n`endif\n"); + assert_eq!(toks.iter().filter_map(macro_name).collect::>(), vec!["ASSERT"]); + assert!(toks + .iter() + .filter(|t| t.kind == TokenKind::Ident) + .all(|t| directive_word(t).is_none())); + } +} diff --git a/crates/vlog_linter/src/registry.rs b/crates/vlog_linter/src/registry.rs index e1c7648..3efcb99 100644 --- a/crates/vlog_linter/src/registry.rs +++ b/crates/vlog_linter/src/registry.rs @@ -85,24 +85,36 @@ pub fn all_rules() -> Vec<&'static dyn Rule> { &rules::banned_declared_name_patterns::BannedDeclaredNamePatterns, &rules::case_missing_default::CaseMissingDefault, &rules::constraint_name_style::ConstraintNameStyle, + &rules::create_object_name_match::CreateObjectNameMatch, + &rules::dff_name_style::DffNameStyle, + &rules::disable_statement::DisableStatement, &rules::duplicate_declaration::DuplicateDeclaration, &rules::empty_item::EmptyItem, + &rules::endif_comment::EndifComment, &rules::enum_name_style::EnumNameStyle, &rules::explicit_begin::ExplicitBegin, + &rules::explicit_function_lifetime::ExplicitFunctionLifetime, &rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType, &rules::explicit_parameter_storage_type::ExplicitParameterStorageType, + &rules::explicit_task_lifetime::ExplicitTaskLifetime, &rules::forbid_consecutive_null_statements::ForbidConsecutiveNullStatements, &rules::forbid_defparam::ForbidDefparam, + &rules::forbid_line_continuations::ForbidLineContinuations, &rules::forbid_negative_array_dim::ForbidNegativeArrayDim, + &rules::forbidden_macro::ForbiddenMacro, &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::legacy_generate_region::LegacyGenerateRegion, + &rules::legacy_genvar_declaration::LegacyGenvarDeclaration, &rules::line_length::LineLength, &rules::macro_name_style::MacroNameStyle, + &rules::macro_string_concatenation::MacroStringConcatenation, &rules::mismatched_labels::MismatchedLabels, + &rules::module_begin_block::ModuleBeginBlock, &rules::module_filename::ModuleFilename, &rules::module_name_style::ModuleNameStyle, &rules::module_parameter::ModuleParameter, @@ -110,6 +122,7 @@ pub fn all_rules() -> Vec<&'static dyn Rule> { &rules::multiply_driven::MultiplyDriven, &rules::no_tabs::NoTabs, &rules::no_trailing_whitespace::NoTrailingWhitespace, + &rules::numeric_format_string_style::NumericFormatStringStyle, &rules::one_module_per_file::OneModulePerFile, &rules::package_filename::PackageFilename, &rules::packed_dimensions_range_ordering::PackedDimensionsRangeOrdering, @@ -117,9 +130,12 @@ pub fn all_rules() -> Vec<&'static dyn Rule> { &rules::parameter_type_name_style::ParameterTypeNameStyle, &rules::plusarg_assignment::PlusargAssignment, &rules::port_name_suffix::PortNameSuffix, + &rules::positive_meaning_parameter_name::PositiveMeaningParameterName, &rules::posix_eof::PosixEof, + &rules::proper_parameter_declaration::ProperParameterDeclaration, &rules::signal_name_style::SignalNameStyle, &rules::struct_union_name_style::StructUnionNameStyle, + &rules::suggest_parentheses::SuggestParentheses, &rules::suspicious_semicolon::SuspiciousSemicolon, &rules::truncated_numeric_literal::TruncatedNumericLiteral, &rules::typedef_enums::TypedefEnums, @@ -129,8 +145,11 @@ pub fn all_rules() -> Vec<&'static dyn Rule> { &rules::undriven_net::UndrivenNet, &rules::unknown_parameter::UnknownParameter, &rules::unknown_port::UnknownPort, + &rules::unpacked_dimensions_range_ordering::UnpackedDimensionsRangeOrdering, &rules::unused_signal::UnusedSignal, &rules::unused_waiver::UnusedWaiver, + &rules::uvm_macro_semicolon::UvmMacroSemicolon, + &rules::v2001_generate_begin::V2001GenerateBegin, &rules::void_cast::VoidCast, &rules::wire_reg_mixup::WireRegMixup, ] diff --git a/crates/vlog_linter/src/rules/create_object_name_match.rs b/crates/vlog_linter/src/rules/create_object_name_match.rs new file mode 100644 index 0000000..0f9621c --- /dev/null +++ b/crates/vlog_linter/src/rules/create_object_name_match.rs @@ -0,0 +1,178 @@ +//! `create-object-name-match` — `type_id::create("x")` names the variable `x`. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::{walk_all_stmts, walk_items}; +use vlog_parser::ast::{Expr, ExprKind, ItemKind, StmtKind}; + +/// See [`Rule::doc`]. +pub struct CreateObjectNameMatch; + +const NAME: &str = "create-object-name-match"; + +impl Rule for CreateObjectNameMatch { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "give `type_id::create` the name of the variable it is assigned to" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn doc(&self) -> &'static str { + "The string handed to `type_id::create()` becomes the object's UVM \ + instance name, and that name is what `uvm_config_db` paths, factory \ + overrides, `+uvm_set_config` plusargs and every report line are \ + written against. When it does not match the handle it was assigned \ + to, a config setting aimed at `env.agent.driver` silently misses the \ + object the reader believes it is aimed at — and nothing fails, it \ + just does not take. Verible's `create-object-name-match` (\"Checks \ + that the 'name' argument of `type_id::create()` matches the assigned \ + variable name.\", enabled by default) is the same rule and the same \ + default.\n\n\ + Judged where Verible judges it: a right-hand side of the shape \ + `::type_id::create(\"name\", …)`, however the type is \ + qualified (`pkg::cls::type_id::create`), assigned to a **plain \ + variable** — a `this.h` or an array element is not one, and neither \ + is a `create` whose first argument is not a string literal. No \ + automatic fix: rewriting the string changes the object's UVM path, \ + and rewriting the variable renames it everywhere; which is meant is \ + the author's to say." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + let mut judge = |lhs: &str, rhs: &Expr| { + let Some(arg) = create_name(rhs) else { return }; + let Some(written) = string_value(arg) else { return }; + if written == lhs { + return; + } + out.push(Violation::new( + NAME, + format!( + "`type_id::create` is named `{written}` but assigned to `{lhs}`; \ + the two must match" + ), + arg.span, + )); + }; + walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind { + StmtKind::Assign { lhs, rhs, .. } => { + if let ExprKind::Ident(name) = &lhs.kind { + judge(name, rhs); + } + } + StmtKind::VarDecl(decl) => { + for declarator in &decl.declarators { + if let Some(init) = &declarator.init { + judge(&declarator.name, init); + } + } + } + _ => {} + }); + walk_items(ctx.file(), &mut |item| { + let ItemKind::DataDecl(decl) = &item.kind else { return }; + for declarator in &decl.declarators { + if let Some(init) = &declarator.init { + judge(&declarator.name, init); + } + } + }); + out + } +} + +/// The first argument of a `…::type_id::create(…)` call, or `None` for +/// anything else. +fn create_name(expr: &Expr) -> Option<&Expr> { + let ExprKind::Call { callee, args, .. } = &expr.kind else { return None }; + let ExprKind::Scope { base, name, .. } = &callee.kind else { return None }; + if name != "create" { + return None; + } + let ExprKind::Scope { name: middle, .. } = &base.kind else { return None }; + if middle != "type_id" { + return None; + } + args.first().map(|arg| &arg.expr) +} + +/// The text of a string literal, without its quotes. +fn string_value(expr: &Expr) -> Option<&str> { + let ExprKind::Str(text) = &expr.kind else { return None }; + text.strip_prefix('"')?.strip_suffix('"') +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + CreateObjectNameMatch.check(&LintContext::new(src, None)) + } + + fn body(text: &str) -> String { + format!( + "class c;\n function automatic void build();\n {text}\n endfunction\nendclass\n" + ) + } + + #[test] + fn flags_a_mismatched_name_and_underlines_the_string() { + let src = body("driver_h = my_driver::type_id::create(\"drv\", this);"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "\"drv\""); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_matching_name_is_what_the_rule_wants() { + for text in [ + "driver_h = my_driver::type_id::create(\"driver_h\", this);", + "driver_h = pkg::my_driver::type_id::create(\"driver_h\");", + ] { + let src = body(text); + assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src)); + } + } + + #[test] + fn a_declaration_with_an_initialiser_is_judged_too() { + let src = body("my_driver driver_h = my_driver::type_id::create(\"drv\");"); + assert_eq!(violations(&src).len(), 1, "{:?}", violations(&src)); + } + + #[test] + fn something_that_is_not_a_type_id_create_is_left_alone() { + for text in [ + "driver_h = my_driver::create(\"drv\");", + "driver_h = my_driver::type_id::get();", + "driver_h = new(\"drv\");", + "driver_h = f(\"drv\");", + ] { + let src = body(text); + assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src)); + } + } + + #[test] + fn a_non_literal_name_or_a_non_plain_target_says_nothing() { + for text in [ + "driver_h = my_driver::type_id::create(name_s, this);", + "this.driver_h = my_driver::type_id::create(\"drv\");", + "agents[0] = my_agent::type_id::create(\"drv\");", + ] { + let src = body(text); + assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src)); + } + } +} diff --git a/crates/vlog_linter/src/rules/dff_name_style.rs b/crates/vlog_linter/src/rules/dff_name_style.rs new file mode 100644 index 0000000..439d5bc --- /dev/null +++ b/crates/vlog_linter/src/rules/dff_name_style.rs @@ -0,0 +1,459 @@ +//! `dff-name-style` — a flip-flop's output and its next-state input are named +//! for each other. + +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_all_stmts, walk_items}; +use vlog_parser::ast::{Expr, ExprKind, ItemKind, Stmt, StmtKind}; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct DffNameStyle; + +const NAME: &str = "dff-name-style"; + +/// Verible's four options. Its `input` / `output` / `waive_ifs_with_conditions` +/// are comma-separated strings there and lists here, which is how every other +/// lucisv list option is spelled; `waive_lhs_regex`'s default is Verible's +/// `(?i)mem.*` written without the inline flag this engine does not implement. +const OPTIONS: &[OptionSpec] = &[ + OptionSpec { + name: "input", + kind: OptionKind::List, + default: OptionDefault::List(&["next", "n", "d"]), + doc: "suffixes that mark the next-state input of a flip-flop", + }, + OptionSpec { + name: "output", + kind: OptionKind::List, + default: OptionDefault::List(&["reg", "r", "ff", "q"]), + doc: "suffixes that mark the registered output of a flip-flop", + }, + OptionSpec { + name: "waive_ifs_with_conditions", + kind: OptionKind::List, + default: OptionDefault::List(&[ + "!rst_ni", + "flush_i", + "!rst_ni || flush_i", + "flush_i || !rst_ni", + ]), + doc: "conditions whose branches are reset or flush paths and are not judged", + }, + OptionSpec { + name: "waive_lhs_regex", + kind: OptionKind::Regex, + default: OptionDefault::Str("[mM][eE][mM].*"), + doc: "names that are not flip-flops at all and are left alone", + }, +]; + +impl Rule for DffNameStyle { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "name a flip-flop's output and its next-state input for each other" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn default_on(&self) -> bool { + false + } + + fn options(&self) -> &'static [OptionSpec] { + OPTIONS + } + + fn doc(&self) -> &'static str { + "The `_q`/`_d` convention makes a design's state visible at a glance: \ + `count_q <= count_d` says \"this is the register, that is the \ + combinational next value\", so a waveform, a schematic and the source \ + all name the same two nets, and a signal called `count_q` driven by \ + a `always_comb` is a mistake the reader can see without following it. \ + Verible's `dff-name-style` (\"Checks that D Flip-Flops use \ + appropriate naming conventions in input/output ports.\", **disabled** \ + by default) is the same rule and the same default, with the same four \ + options.\n\n\ + Two things are checked. **In an `always_ff`**, a nonblocking \ + assignment's left-hand side must end with one of the `output` \ + suffixes (`_q`, `_r`, `_ff`, `_reg`, optionally with a pipeline \ + number: `data_q2`); and when its right-hand side is a plain name \ + ending with one of the `input` suffixes (`_d`, `_n`, `_next`), the \ + two must share a base — `data_q <= data_d` is right, `data_q <= \ + other_d` is not. **Outside one**, a blocking or continuous \ + assignment to a name ending in an `output` suffix is reported: that \ + name promises a register and is not one.\n\n\ + Only a **plain identifier** is judged on either side; an indexed, \ + member-selected or concatenated target is not something a naming \ + convention can speak about. A branch whose `if` condition is one of \ + `waive_ifs_with_conditions` is skipped, which is what keeps reset \ + and flush paths quiet, and a name matching `waive_lhs_regex` is \ + skipped entirely (memories are not flip-flops). Conditions are \ + compared ignoring whitespace, so `!rst_ni` and `! rst_ni` are the \ + same waiver. No automatic fix: renaming a signal is a rename." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let settings = Settings::read(ctx); + let mut out = Vec::new(); + registered(ctx, &settings, &mut out); + unregistered(ctx, &settings, &mut out); + out.sort_by_key(|violation| (violation.span.start, violation.span.end)); + out + } +} + +/// The four options, read once for the whole file. +struct Settings { + input: Vec, + output: Vec, + waived_conditions: Vec, + waived_lhs: Option, +} + +impl Settings { + fn read(ctx: &LintContext) -> Settings { + Settings { + input: ctx.option_list(NAME, "input"), + output: ctx.option_list(NAME, "output"), + waived_conditions: ctx + .option_list(NAME, "waive_ifs_with_conditions") + .iter() + .map(|text| squeeze(text)) + .collect(), + waived_lhs: ctx.option_pattern(NAME, "waive_lhs_regex"), + } + } + + /// Whether this left-hand side is one the project asked not to judge. + fn waives(&self, name: &str) -> bool { + self.waived_lhs.as_ref().is_some_and(|pattern| pattern.is_match(name)) + } +} + +/// The `always_ff` half: every nonblocking assignment inside one. +fn registered(ctx: &LintContext, settings: &Settings, out: &mut Vec) { + walk_items(ctx.file(), &mut |item| { + let ItemKind::Always { kw, stmt } = &item.kind else { return }; + if kw != "always_ff" { + return; + } + let mut conditions: Vec = Vec::new(); + clocked(ctx, settings, stmt, &mut conditions, out); + }); +} + +/// Walks one `always_ff` body, remembering which `if` conditions hold. +fn clocked( + ctx: &LintContext, + settings: &Settings, + stmt: &Stmt, + conditions: &mut Vec, + out: &mut Vec, +) { + match &stmt.kind { + StmtKind::Assign { lhs, rhs, op, .. } if op == "<=" => { + if conditions.iter().any(|cond| settings.waived_conditions.contains(cond)) { + return; + } + judge_flop(settings, lhs, rhs, out); + } + StmtKind::If { cond, then, els, .. } => { + conditions.push(squeeze(text_of(ctx, cond.span))); + clocked(ctx, settings, then, conditions, out); + conditions.pop(); + if let Some(els) = els { + clocked(ctx, settings, els, conditions, out); + } + } + StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => { + for inner in stmts { + clocked(ctx, settings, inner, conditions, out); + } + } + StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => { + for case_item in items { + clocked(ctx, settings, &case_item.stmt, conditions, out); + } + } + StmtKind::Labeled { stmt: inner, .. } + | StmtKind::For { body: inner, .. } + | StmtKind::While { body: inner, .. } + | StmtKind::DoWhile { body: inner, .. } + | StmtKind::Repeat { body: inner, .. } + | StmtKind::Forever { body: inner } + | StmtKind::Foreach { body: inner, .. } => clocked(ctx, settings, inner, conditions, out), + StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => { + clocked(ctx, settings, inner, conditions, out) + } + _ => {} + } +} + +/// One `q <= d` inside an `always_ff`. +fn judge_flop(settings: &Settings, lhs: &Expr, rhs: &Expr, out: &mut Vec) { + let Some(target) = plain_name(lhs) else { return }; + if settings.waives(target) { + return; + } + let Some(base) = base_of(target, &settings.output) else { + out.push(Violation::new( + NAME, + format!( + "`{target}` is assigned in an `always_ff` but does not end with {}", + one_of(&settings.output) + ), + lhs.span, + )); + return; + }; + if base.is_empty() { + out.push(Violation::new( + NAME, + format!("`{target}` is nothing but a flip-flop suffix; name the signal too"), + lhs.span, + )); + return; + } + let Some(source) = plain_name(rhs) else { return }; + let Some(source_base) = base_of(source, &settings.input) else { return }; + if source_base != base { + out.push(Violation::new( + NAME, + format!( + "`{target}` is driven by `{source}`; the parts before the suffixes must \ + match, but `{base}` is not `{source_base}`" + ), + rhs.span, + )); + } +} + +/// The other half: a name that promises a register, driven by something that +/// is not one. +fn unregistered(ctx: &LintContext, settings: &Settings, out: &mut Vec) { + let mut judge = |lhs: &Expr| { + let Some(target) = plain_name(lhs) else { return }; + if settings.waives(target) { + return; + } + if base_of(target, &settings.output).is_some_and(|base| !base.is_empty()) { + out.push(Violation::new( + NAME, + format!( + "`{target}` is named like a flip-flop output but is not driven by a \ + nonblocking assignment in an `always_ff`" + ), + lhs.span, + )); + } + }; + walk_items(ctx.file(), &mut |item| { + let ItemKind::ContAssign(assign) = &item.kind else { return }; + for pair in &assign.assigns { + judge(&pair.lhs); + } + }); + // A blocking assignment anywhere — in an `always_comb`, an `initial`, or + // inside the `always_ff` itself, which is the shape the rule most wants. + walk_all_stmts(ctx.file(), &mut |stmt| { + let StmtKind::Assign { lhs, op, .. } = &stmt.kind else { return }; + if op == "<=" { + return; + } + judge(lhs); + }); +} + +/// The name of a plain identifier, or `None` for any other target. +fn plain_name(expr: &Expr) -> Option<&str> { + match &expr.kind { + ExprKind::Ident(name) => Some(name), + _ => None, + } +} + +/// The part of `name` before its `_[digits]` tail, or `None` when it +/// carries none of `suffixes`. +fn base_of<'a>(name: &'a str, suffixes: &[String]) -> Option<&'a str> { + let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit()); + for suffix in suffixes { + if let Some(base) = trimmed.strip_suffix(suffix.as_str()) { + if let Some(base) = base.strip_suffix('_') { + return Some(base); + } + // `_q` on its own: a suffix with nothing in front of it. + if base.is_empty() && trimmed.len() == suffix.len() { + return Some(""); + } + } + } + None +} + +/// `` `_q`, `_r` or `_ff` `` — the suffix list, as a message says it. +fn one_of(suffixes: &[String]) -> String { + let quoted: Vec = suffixes.iter().map(|s| format!("`_{s}`")).collect(); + match quoted.split_last() { + Some((last, [])) => last.clone(), + Some((last, rest)) => format!("{} or {last}", rest.join(", ")), + None => "a registered-output suffix".to_string(), + } +} + +/// The source text of a span. +fn text_of<'a>(ctx: &'a LintContext, span: TextRange) -> &'a str { + ctx.source().get(span.as_range()).unwrap_or("") +} + +/// The same text with every space taken out, so `!rst_ni` and `! rst_ni` are +/// one waiver rather than two. +fn squeeze(text: &str) -> String { + text.chars().filter(|c| !c.is_whitespace()).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::options::RuleOptions; + + fn violations(src: &str) -> Vec { + DffNameStyle.check(&LintContext::new(src, None)) + } + + fn with(src: &str, key: &str, raw: &str) -> Vec { + let mut options = RuleOptions::new(); + options.set_raw(NAME, key, raw).expect("accepted"); + DffNameStyle.check(&LintContext::new(src, None).with_options(&options)) + } + + fn flop(body: &str) -> String { + format!("module m;\n always_ff @(posedge clk) begin\n {body}\n end\nendmodule\n") + } + + #[test] + fn the_convention_is_clean() { + for body in [ + "data_q <= data_d;", + "data_r <= data_n;", + "data_ff <= data_next;", + "data_reg <= data_d;", + "data_q2 <= data_d2;", + "data_q <= other_signal;", + "data_q <= a + b;", + ] { + let src = flop(body); + assert!(violations(&src).is_empty(), "{body}: {:?}", violations(&src)); + } + } + + #[test] + fn flags_a_registered_name_without_a_suffix() { + let src = flop("data <= data_d;"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "data"); + assert!(found[0].message.contains("`_q`"), "{}", found[0].message); + assert!(found[0].fix.is_none()); + } + + #[test] + fn flags_a_mismatched_pair_and_points_at_the_source() { + let src = flop("a_q <= b_n;"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "b_n"); + assert!(found[0].message.contains("`a` is not `b`"), "{}", found[0].message); + } + + #[test] + fn a_bare_suffix_names_nothing() { + let src = flop("_q <= data_d;"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!( + found[0].message.contains("nothing but a flip-flop suffix"), + "{}", + found[0].message + ); + } + + #[test] + fn a_reset_branch_is_waived_whatever_its_spacing() { + for cond in ["!rst_ni", "! rst_ni", "flush_i", "!rst_ni || flush_i"] { + let src = flop(&format!("if ({cond}) data <= '0; else data_q <= data_d;")); + assert!(violations(&src).is_empty(), "{cond}: {:?}", violations(&src)); + } + } + + #[test] + fn a_condition_that_is_not_waived_is_still_judged() { + let src = flop("if (enable_i) data <= data_d;"); + assert_eq!(violations(&src).len(), 1, "{:?}", violations(&src)); + } + + #[test] + fn a_memory_name_is_waived_by_the_default_pattern() { + for name in ["mem_array", "MEM_ARRAY", "Memory"] { + let src = flop(&format!("{name} <= data_d;")); + assert!(violations(&src).is_empty(), "{name}: {:?}", violations(&src)); + } + } + + #[test] + fn a_flip_flop_name_driven_by_anything_else_is_reported() { + let combinational = "module m;\n always_comb data_q = data_d;\nendmodule\n"; + assert_eq!(violations(combinational).len(), 1, "{:?}", violations(combinational)); + let continuous = "module m;\n assign data_q = data_d;\nendmodule\n"; + assert_eq!(violations(continuous).len(), 1, "{:?}", violations(continuous)); + let blocking_in_ff = flop("data_q = data_d;"); + assert_eq!(violations(&blocking_in_ff).len(), 1, "{:?}", violations(&blocking_in_ff)); + } + + #[test] + fn a_plain_signal_driven_combinationally_is_nobodys_business() { + let src = "module m;\n assign data_d = a + b;\n always_comb next = 1;\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_non_plain_target_is_not_judged() { + for body in ["data[0] <= data_d;", "s.f <= data_d;", "{a, b} <= data_d;"] { + let src = flop(body); + assert!(violations(&src).is_empty(), "{body}: {:?}", violations(&src)); + } + } + + #[test] + fn the_suffix_lists_are_configurable() { + let src = flop("data_ptr <= data_nxt;"); + assert_eq!(violations(&src).len(), 1); + let mut options = RuleOptions::new(); + options.set_raw(NAME, "output", "[\"ptr\"]").expect("accepted"); + options.set_raw(NAME, "input", "[\"nxt\"]").expect("accepted"); + let found = DffNameStyle.check(&LintContext::new(&src, None).with_options(&options)); + assert!(found.is_empty(), "{found:?}"); + } + + #[test] + fn the_lhs_waiver_pattern_is_configurable() { + let src = flop("scratch <= data_d;"); + assert_eq!(violations(&src).len(), 1); + assert!(with(&src, "waive_lhs_regex", "\"scratch.*\"").is_empty()); + } + + #[test] + fn the_waived_conditions_are_configurable() { + let src = flop("if (my_reset) data <= '0;"); + assert_eq!(violations(&src).len(), 1); + assert!(with(&src, "waive_ifs_with_conditions", "[\"my_reset\"]").is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/disable_statement.rs b/crates/vlog_linter/src/rules/disable_statement.rs new file mode 100644 index 0000000..326f5e9 --- /dev/null +++ b/crates/vlog_linter/src/rules/disable_statement.rs @@ -0,0 +1,157 @@ +//! `disable-statement` — `disable` only a sequential block, or `disable fork`. + +use std::collections::BTreeSet; + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::{walk_all_stmts, walk_items}; +use vlog_parser::ast::{ItemKind, SourceFile, StmtKind}; + +/// See [`Rule::doc`]. +pub struct DisableStatement; + +const NAME: &str = "disable-statement"; + +impl Rule for DisableStatement { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "`disable` a sequential block or a task, and write `disable fork` for processes" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn default_on(&self) -> bool { + false + } + + fn doc(&self) -> &'static str { + "`disable label` terminates the named sequential block, and \ + `disable fork` terminates the calling process's children (IEEE 1800 \ + §9.6.2, §9.6.3). Naming a `fork` block instead of writing \ + `disable fork` is the mistake this rule exists for: it reads as \ + though it kills the forked processes and does something else \ + entirely, and in the common `fork … join_none` idiom it kills \ + nothing at all. Verible's `disable-statement` (\"Checks that there \ + are no occurrences of `disable some_label` if label refers to \ + non-sequential blocks.\", **disabled** by default) is the same rule \ + and the same default.\n\n\ + What counts as a valid target here is the label of a \ + `begin : name` block, a statement label (`name : begin`) — and, \ + **wider than Verible**, the name of a task or function declared in \ + the same file, because `disable task_name` is a legal and ordinary \ + thing to write (§9.6.2) and reporting it would be a false positive. \ + A name lucisv cannot see at all — a block in another file, a label a \ + macro produces — is therefore reported; that is the rule's one \ + false-positive mode and the reason it ships off. No automatic fix: \ + whether the author meant `disable fork` or a different label is not \ + something the source says." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let targets = disableable(ctx.file()); + let mut out = Vec::new(); + walk_all_stmts(ctx.file(), &mut |stmt| { + let StmtKind::Disable(name) = &stmt.kind else { return }; + // `disable fork` is the keyword form, not a label. + if name == "fork" || targets.contains(name.as_str()) { + return; + } + out.push(Violation::new( + NAME, + format!( + "`disable {name}` names no sequential block or task; write `disable fork` \ + to stop forked processes" + ), + stmt.span, + )); + }); + out + } +} + +/// Every name a `disable` may legitimately mention in this file: the labels of +/// sequential blocks and statement labels, plus the tasks and functions the +/// file declares. +fn disableable(file: &SourceFile) -> BTreeSet { + let mut out = BTreeSet::new(); + walk_all_stmts(file, &mut |stmt| match &stmt.kind { + StmtKind::Block { label: Some(label), .. } => { + out.insert(label.clone()); + } + StmtKind::Labeled { name, stmt: inner, .. } => { + if matches!(inner.kind, StmtKind::Block { .. }) { + out.insert(name.clone()); + } + } + _ => {} + }); + walk_items(file, &mut |item| match &item.kind { + ItemKind::Task(decl) => { + out.insert(decl.name.clone()); + } + ItemKind::Function(decl) => { + out.insert(decl.name.clone()); + } + _ => {} + }); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + DisableStatement.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_disable_of_a_fork_label() { + let src = "module m;\n initial begin\n fork : threads\n join_none\n \ + disable threads;\n end\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "disable threads;"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn disable_fork_is_the_spelling_the_rule_asks_for() { + let src = "module m;\n initial begin\n fork\n join_none\n disable fork;\n \ + end\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_sequential_block_label_is_a_valid_target() { + let src = "module m;\n initial begin : seq\n disable seq;\n end\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_statement_label_on_a_block_counts_too() { + let src = "module m;\n initial begin\n outer : begin\n disable outer;\n \ + end\n end\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_task_of_the_same_file_is_a_legal_target() { + let src = "module m;\n task automatic t();\n endtask\n initial begin\n \ + disable t;\n end\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_name_this_file_does_not_declare_is_reported() { + let src = "module m;\n initial begin\n disable somewhere_else;\n end\nendmodule\n"; + assert_eq!(violations(src).len(), 1); + } +} diff --git a/crates/vlog_linter/src/rules/endif_comment.rs b/crates/vlog_linter/src/rules/endif_comment.rs new file mode 100644 index 0000000..10513e8 --- /dev/null +++ b/crates/vlog_linter/src/rules/endif_comment.rs @@ -0,0 +1,194 @@ +//! `endif-comment` — say which `` `ifdef `` an `` `endif `` closes. + +use crate::context::LintContext; +use crate::preproc::{directive_operand, directive_word}; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::{Applicability, Fix, Violation}; +use vlog_parser::span::TextRange; +use vlog_parser::token::Token; + +/// See [`Rule::doc`]. +pub struct EndifComment; + +const NAME: &str = "endif-comment"; + +impl Rule for EndifComment { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "name the condition an `` `endif `` closes in a comment beside it" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn default_on(&self) -> bool { + false + } + + fn fix(&self) -> Option { + Some(Applicability::Safe) + } + + fn doc(&self) -> &'static str { + "A bare `` `endif `` two hundred lines below its `` `ifdef `` tells \ + the reader nothing: which condition just ended, and whether the \ + nesting is what they think it is, both take a scroll to answer. \ + `` `endif // SYNTHESIS `` answers them in place, which is the same \ + argument `mismatched-labels` makes for `end : name`. Verible's \ + `endif-comment` (\"Checks that a Verilog `` `endif `` directive is \ + followed by a matching comment.\", **disabled** by default) is the \ + same rule and the same default.\n\n\ + The comment must **name the condition** — any comment on the \ + `` `endif ``'s own line that writes the macro name as a word will \ + do, so `// SYNTHESIS`, `` // `ifdef SYNTHESIS `` and `/* SYNTHESIS \ + */` all pass. An `` `endif `` whose `` `ifdef `` lucisv cannot see \ + (an unbalanced file, a condition opened in an included header) is \ + left alone: there is no name to ask for.\n\n\ + The fix is **safe** and only offered where there is no comment at \ + all: it appends `` // `` after the directive, adding text and \ + removing none. A comment that is there but names something else is \ + reported without a fix — rewriting somebody's words is not a repair." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut open: Vec> = Vec::new(); + let mut out = Vec::new(); + for token in ctx.tokens() { + match directive_word(token) { + Some("ifdef") | Some("ifndef") => { + open.push(directive_operand(token).map(str::to_string)) + } + Some("endif") => { + // An `endif` with nothing open is an unbalanced file, or a + // condition opened in an included header: no name to ask + // for, so nothing to say. + let Some(Some(name)) = open.pop() else { continue }; + if let Some(violation) = judge(ctx, token, &name) { + out.push(violation); + } + } + _ => {} + } + } + out + } +} + +/// The finding this `` `endif `` earns, or `None` when its comment names the +/// condition. +fn judge(ctx: &LintContext, token: &Token, name: &str) -> Option { + let beside: Vec<&str> = ctx + .comments() + .into_iter() + .filter(|comment| comment.line == token.line && comment.span.start >= token.span.end) + .map(|comment| comment.text.as_str()) + .collect(); + if beside.iter().any(|text| names(text, name)) { + return None; + } + let violation = Violation::new( + NAME, + format!("`endif` does not say what it closes; write `// {name}`"), + token.span, + ); + match beside.is_empty() { + true => Some(violation.with_fix(Fix::safe(vec![( + TextRange::new(token.span.end, token.span.end), + format!(" // {name}"), + )]))), + // There is a comment; it just names something else. Replacing it would + // throw away what somebody wrote. + false => Some(violation), + } +} + +/// True when `text` writes `name` as a whole word. +fn names(text: &str, name: &str) -> bool { + let is_part = |c: char| c == '_' || c == '$' || c.is_ascii_alphanumeric(); + let mut rest = text; + while let Some(at) = rest.find(name) { + let before = rest[..at].chars().next_back(); + let after = rest[at + name.len()..].chars().next(); + if !before.is_some_and(is_part) && !after.is_some_and(is_part) { + return true; + } + rest = &rest[at + name.len()..]; + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::violation::apply_fixes; + + fn violations(src: &str) -> Vec { + EndifComment.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_bare_endif_and_offers_the_comment() { + let src = "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "`endif"); + let fixed = apply_fixes(src, &found, false); + assert_eq!(fixed.output, "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif // SYNTHESIS\n"); + assert!(violations(&fixed.output).is_empty(), "the fix settles"); + } + + #[test] + fn a_naming_comment_of_any_shape_passes() { + for comment in ["// SYNTHESIS", "// `ifdef SYNTHESIS", "/* SYNTHESIS */", "//SYNTHESIS"] { + let src = format!("`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif {comment}\n"); + assert!(violations(&src).is_empty(), "{comment}: {:?}", violations(&src)); + } + } + + #[test] + fn a_comment_naming_something_else_is_reported_without_a_fix() { + let src = "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif // done\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].fix.is_none(), "somebody's comment is not ours to rewrite"); + } + + #[test] + fn a_name_that_only_contains_the_condition_is_not_a_match() { + let src = "`ifdef SYN\nmodule m;\nendmodule\n`endif // SYNTHESIS\n"; + assert_eq!(violations(src).len(), 1, "{:?}", violations(src)); + } + + #[test] + fn nesting_pairs_each_endif_with_its_own_condition() { + let src = "`ifdef A\n`ifdef B\nmodule m;\nendmodule\n`endif\n`endif\n"; + let found = violations(src); + assert_eq!(found.len(), 2, "{found:?}"); + assert!(found[0].message.contains("// B"), "{}", found[0].message); + assert!(found[1].message.contains("// A"), "{}", found[1].message); + } + + #[test] + fn an_ifndef_and_an_else_are_handled_like_the_ifdef() { + let src = "`ifndef A\nmodule m;\nendmodule\n`else\nmodule n;\nendmodule\n`endif\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("// A"), "{}", found[0].message); + } + + #[test] + fn an_unbalanced_endif_has_no_name_to_ask_for() { + assert!(violations("`endif\nmodule m;\nendmodule\n").is_empty()); + } + + #[test] + fn a_comment_on_the_next_line_is_not_beside_the_endif() { + let src = "`ifdef A\nmodule m;\nendmodule\n`endif\n// A\n"; + assert_eq!(violations(src).len(), 1); + } +} diff --git a/crates/vlog_linter/src/rules/explicit_function_lifetime.rs b/crates/vlog_linter/src/rules/explicit_function_lifetime.rs new file mode 100644 index 0000000..0804737 --- /dev/null +++ b/crates/vlog_linter/src/rules/explicit_function_lifetime.rs @@ -0,0 +1,149 @@ +//! `explicit-function-lifetime` — say `automatic` or `static` outside a class. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::{walk_items_scoped, ItemScope}; +use vlog_parser::ast::ItemKind; + +/// See [`Rule::doc`]. +pub struct ExplicitFunctionLifetime; + +const NAME: &str = "explicit-function-lifetime"; + +/// The two words that state a lifetime, wherever a subroutine writes them. +pub(crate) const LIFETIMES: [&str; 2] = ["automatic", "static"]; + +impl Rule for ExplicitFunctionLifetime { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "state `automatic` or `static` on a function declared outside a class" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn doc(&self) -> &'static str { + "A function with no stated lifetime is `static` in a module and \ + `automatic` in a class (IEEE 1800 §13.4.2), and a static function's \ + locals are shared by every call — so one written without the keyword \ + is a re-entrancy bug waiting for the second caller, and a reader \ + cannot tell whether the author knew. Writing the word costs nine \ + characters and removes the question. Verible's \ + `explicit-function-lifetime` (\"Checks that every function declared \ + outside of a class is declared with an explicit lifetime.\", enabled \ + by default) is the same rule and the same default; a class method is \ + exempt in both, because there the default is already the safe one.\n\n\ + A body-less **prototype** — `extern function f;`, a `pure virtual`, a \ + DPI import — is not judged: it declares no locals, and the definition \ + that follows is where the lifetime belongs. Nor is an **out-of-body \ + definition** (`function cls::f(...); … endfunction`), which is \ + **wider than Verible**: lexically it sits outside the class, and \ + Verible reports it, but it *is* a class method and its lifetime is \ + already automatic — 948 of the 960 opentitan findings this rule and \ + its task twin produced before the exemption were exactly that shape. \ + No automatic fix: \ + `automatic` is the answer a reader expects and `static` is what the \ + language would have picked, so choosing between them changes what \ + the code does." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_items_scoped(ctx.file(), &mut |scope, item| { + let ItemKind::Function(decl) = &item.kind else { return }; + // An out-of-body definition (`function cls::f(...)`) is a class + // method written outside the class body; `scope` is non-empty for + // exactly those. + if scope == ItemScope::Class + || !decl.scope.is_empty() + || decl.is_prototype + || decl.dpi.is_some() + { + return; + } + if decl.qualifiers.iter().any(|q| LIFETIMES.contains(&q.text.as_str())) { + return; + } + out.push(Violation::new( + NAME, + format!( + "function `{}` has no explicit lifetime; write `automatic` or `static`", + decl.name + ), + decl.name_span, + )); + }); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + ExplicitFunctionLifetime.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_module_function_and_points_at_its_name() { + let src = "module m;\n function int f(int x);\n return x;\n endfunction\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "f"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn either_keyword_satisfies_the_rule() { + for kw in ["automatic", "static"] { + let src = format!( + "module m;\n function {kw} int f(int x);\n return x;\n endfunction\nendmodule\n" + ); + assert!(violations(&src).is_empty(), "{kw}: {:?}", violations(&src)); + } + } + + #[test] + fn a_class_method_is_exempt() { + let src = "class c;\n function int f(int x);\n return x;\n endfunction\nendclass\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_package_or_file_scope_function_is_judged() { + let pkg = "package p;\n function int f();\n return 0;\n endfunction\nendpackage\n"; + assert_eq!(violations(pkg).len(), 1); + let top = "function int f();\n return 0;\nendfunction\n"; + assert_eq!(violations(top).len(), 1); + } + + #[test] + fn a_prototype_declares_no_locals() { + let src = "class c;\n extern function int f();\nendclass\n\ + import \"DPI-C\" function int c_f(input int x);\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + /// An `extern` method defined outside its class body is still a class + /// method; Verible reports it, lucisv does not (see the rule's doc). + #[test] + fn an_out_of_body_definition_is_a_class_method() { + let src = "class c;\n extern function int f();\nendclass\n\ + function c::f();\n return 0;\nendfunction\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_class_nested_in_a_package_is_still_a_class() { + let src = "package p;\n class c;\n function int f();\n return 0;\n \ + endfunction\n endclass\nendpackage\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/explicit_task_lifetime.rs b/crates/vlog_linter/src/rules/explicit_task_lifetime.rs new file mode 100644 index 0000000..13dfa38 --- /dev/null +++ b/crates/vlog_linter/src/rules/explicit_task_lifetime.rs @@ -0,0 +1,120 @@ +//! `explicit-task-lifetime` — say `automatic` or `static` outside a class. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::rules::explicit_function_lifetime::LIFETIMES; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::{walk_items_scoped, ItemScope}; +use vlog_parser::ast::ItemKind; + +/// See [`Rule::doc`]. +pub struct ExplicitTaskLifetime; + +const NAME: &str = "explicit-task-lifetime"; + +impl Rule for ExplicitTaskLifetime { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "state `automatic` or `static` on a task declared outside a class" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn doc(&self) -> &'static str { + "The same argument `explicit-function-lifetime` makes, and worse: a \ + task can block, so a `static` one is routinely called from two \ + processes at once and its locals are one set of variables shared \ + between them (IEEE 1800 §13.4.2). A task with no stated lifetime is \ + `static` in a module and `automatic` in a class, and nothing in the \ + source says which the author meant. Verible's \ + `explicit-task-lifetime` (\"Checks that every task declared outside \ + of a class is declared with an explicit lifetime.\", enabled by \ + default) is the same rule and the same default.\n\n\ + A body-less prototype, a DPI import and an out-of-body definition \ + (`task cls::t(); … endtask`) are not judged, and no automatic fix is \ + offered — all for the reasons `explicit-function-lifetime` gives." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_items_scoped(ctx.file(), &mut |scope, item| { + let ItemKind::Task(decl) = &item.kind else { return }; + // An out-of-body definition (`function cls::f(...)`) is a class + // method written outside the class body; `scope` is non-empty for + // exactly those. + if scope == ItemScope::Class + || !decl.scope.is_empty() + || decl.is_prototype + || decl.dpi.is_some() + { + return; + } + if decl.qualifiers.iter().any(|q| LIFETIMES.contains(&q.text.as_str())) { + return; + } + out.push(Violation::new( + NAME, + format!( + "task `{}` has no explicit lifetime; write `automatic` or `static`", + decl.name + ), + decl.name_span, + )); + }); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + ExplicitTaskLifetime.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_module_task_and_points_at_its_name() { + let src = "module m;\n task t();\n endtask\nendmodule\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 either_keyword_satisfies_the_rule() { + for kw in ["automatic", "static"] { + let src = format!("module m;\n task {kw} t();\n endtask\nendmodule\n"); + assert!(violations(&src).is_empty(), "{kw}: {:?}", violations(&src)); + } + } + + #[test] + fn a_class_method_is_exempt() { + assert!(violations("class c;\n task t();\n endtask\nendclass\n").is_empty()); + } + + #[test] + fn a_function_is_the_other_rules_business() { + let src = "module m;\n function int f();\n return 0;\n endfunction\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_prototype_declares_no_locals() { + assert!(violations("class c;\n extern task t();\nendclass\n").is_empty()); + } + + #[test] + fn an_out_of_body_definition_is_a_class_method() { + let src = "class c;\n extern task t();\nendclass\ntask c::t();\nendtask\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/forbid_line_continuations.rs b/crates/vlog_linter/src/rules/forbid_line_continuations.rs new file mode 100644 index 0000000..5e394f3 --- /dev/null +++ b/crates/vlog_linter/src/rules/forbid_line_continuations.rs @@ -0,0 +1,129 @@ +//! `forbid-line-continuations` — no `\` breaking a string literal. + +use crate::context::LintContext; +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 ForbidLineContinuations; + +const NAME: &str = "forbid-line-continuations"; + +impl Rule for ForbidLineContinuations { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "do not break a string literal across lines with a backslash continuation" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn doc(&self) -> &'static str { + "A string broken with a backslash at end of line keeps every character \ + of the next line, its leading indentation included — so re-indenting \ + the file changes the string's *value*, and a formatter, a rebase or \ + a careless editor silently alters what the design prints. It is also \ + invisible: the second line looks like code. The portable spelling is \ + string concatenation, `{\"first \", \"second\"}`, which the compiler \ + folds and nothing can re-indent. Verible's \ + `forbid-line-continuations` (\"Checks that there are no occurrences \ + of `\\` when breaking string literal lines.\", enabled by default) is \ + the same rule and the same default.\n\n\ + Only a continuation *inside a string literal* is judged: a `` `define \ + `` body written across lines with a `\\` is the only way the language \ + gives to write a multi-line macro, and this rule says nothing about \ + it. No automatic fix — replacing the continuation with a \ + concatenation has to decide where the whitespace of the second line \ + belongs, and only the author knows." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + for token in ctx.tokens().iter().filter(|t| t.kind == TokenKind::String) { + for offset in continuations(&token.text) { + let start = token.span.start + offset as u32; + out.push(Violation::new( + NAME, + "string literal is broken with a `\\` line continuation; write \ + `{\"...\", \"...\"}` instead", + TextRange::new(start, start + 1), + )); + } + } + out + } +} + +/// Byte offsets of every backslash that continues `text` onto the next line. +/// +/// A `\\` is an escaped backslash and continues nothing, so the scan steps +/// over both characters — otherwise `"a\\\\\n"` would be read as a +/// continuation of its own escape. +fn continuations(text: &str) -> Vec { + let bytes = text.as_bytes(); + let mut out = Vec::new(); + let mut i = 0usize; + while i + 1 < bytes.len() { + if bytes[i] != b'\\' { + i += 1; + continue; + } + match bytes[i + 1] { + b'\n' => out.push(i), + // `\r\n` counts too: the file's line endings are not the point. + b'\r' if bytes.get(i + 2) == Some(&b'\n') => out.push(i), + _ => {} + } + i += 2; + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + ForbidLineContinuations.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_the_backslash_that_breaks_a_string() { + let src = "module m;\n initial $display(\"a long \\\n string\");\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "\\"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_one_line_string_is_clean() { + let src = "module m;\n initial $display(\"a long string\");\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn an_ordinary_escape_is_not_a_continuation() { + let src = "module m;\n initial $display(\"tab\\t quote\\\" slash\\\\ end\");\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_multi_line_define_is_not_a_string() { + let src = "`define TWO_LINES \\\n wire a; \\\n wire b;\nmodule m;\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn every_break_of_one_string_is_reported() { + let src = "module m;\n initial $display(\"a \\\n b \\\n c\");\nendmodule\n"; + assert_eq!(violations(src).len(), 2, "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/forbidden_macro.rs b/crates/vlog_linter/src/rules/forbidden_macro.rs new file mode 100644 index 0000000..dfdf889 --- /dev/null +++ b/crates/vlog_linter/src/rules/forbidden_macro.rs @@ -0,0 +1,152 @@ +//! `forbidden-macro` — macros a project has decided nothing should call. + +use crate::context::LintContext; +use crate::options::{OptionDefault, OptionKind, OptionSpec}; +use crate::preproc::macro_name; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct ForbiddenMacro; + +const NAME: &str = "forbidden-macro"; + +/// The one option, spelled as this rule's own since Verible's list is a +/// compile-time constant with no parameter to change it. +const OPTIONS: &[OptionSpec] = &[OptionSpec { + name: "macros", + kind: OptionKind::List, + // Verible's own list, name for name: `uvm_warning` and nothing else. + default: OptionDefault::List(&["uvm_warning"]), + doc: "macro names nothing may invoke, with or without the leading backtick", +}]; + +impl Rule for ForbiddenMacro { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "do not invoke a forbidden macro" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn options(&self) -> &'static [OptionSpec] { + OPTIONS + } + + fn doc(&self) -> &'static str { + "Verible's `forbidden-macro` (\"Checks that no forbidden macro calls \ + are used.\", enabled by default) ships one name: `` `uvm_warning ``. \ + A UVM warning is a message nothing acts on — the test keeps running, \ + the regression stays green, and the condition that produced it is \ + rediscovered later by somebody reading a log. The UVM style guides \ + that ban it want the choice made at the point of failure: \ + `` `uvm_error `` if the test should fail, `` `uvm_info `` if it \ + really is only information.\n\n\ + Verible hard-codes its list; lucisv makes it the `macros` option, so \ + a project that has banned `` `uvm_fatal `` or a macro of its own \ + writes them down instead of asking for a new rule. An entry may be \ + written with or without its backtick — `\"uvm_warning\"` and \ + `` \"`uvm_warning\"`` name the same macro. An empty list turns the \ + rule off as surely as `--ignore` does. No automatic fix: which \ + replacement is right is exactly the judgment the rule is asking for." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let forbidden: Vec = ctx + .option_list(NAME, "macros") + .iter() + .map(|entry| entry.trim_start_matches('`').to_string()) + .collect(); + if forbidden.is_empty() { + return Vec::new(); + } + ctx.tokens() + .iter() + .filter_map(|token| { + let name = macro_name(token)?; + if !forbidden.iter().any(|entry| entry == name) { + return None; + } + // The backtick and the name, not the arguments after them. + let end = token.span.start + 1 + name.len() as u32; + Some(Violation::new( + NAME, + format!("`` `{name} `` is a forbidden macro"), + TextRange::new(token.span.start, end), + )) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::options::RuleOptions; + + fn violations(src: &str) -> Vec { + ForbiddenMacro.check(&LintContext::new(src, None)) + } + + fn with(src: &str, raw: &str) -> Vec { + let mut options = RuleOptions::new(); + options.set_raw(NAME, "macros", raw).expect("accepted"); + ForbiddenMacro.check(&LintContext::new(src, None).with_options(&options)) + } + + #[test] + fn flags_the_default_name_and_underlines_the_invocation() { + let src = "module m;\n initial `uvm_warning(\"A\", \"B\");\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "`uvm_warning"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn the_neighbouring_uvm_macros_are_left_alone() { + let src = "module m;\n\ + \x20 initial begin\n\ + \x20 `uvm_info(\"A\", \"B\", UVM_LOW)\n\ + \x20 `uvm_error(\"A\", \"B\")\n\ + \x20 `uvm_fatal(\"A\", \"B\")\n\ + \x20 end\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_name_that_only_starts_the_same_is_not_a_hit() { + let src = "module m;\n initial `uvm_warning_once(\"A\");\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn an_identifier_or_a_string_with_the_name_in_it_is_not_an_invocation() { + let src = "module m;\n wire uvm_warning;\n initial $display(\"`uvm_warning\");\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn the_option_replaces_the_list_and_accepts_either_spelling() { + let src = "module m;\n initial begin\n `uvm_warning(\"A\", \"B\")\n \ + `my_macro(1)\n end\nendmodule\n"; + assert_eq!(with(src, "[\"my_macro\"]").len(), 1); + assert_eq!(with(src, "[\"`my_macro\"]").len(), 1); + assert_eq!(with(src, "[\"uvm_warning\", \"my_macro\"]").len(), 2); + } + + #[test] + fn an_empty_list_reports_nothing() { + let src = "module m;\n initial `uvm_warning(\"A\", \"B\");\nendmodule\n"; + assert!(with(src, "[]").is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/invalid_system_task_function.rs b/crates/vlog_linter/src/rules/invalid_system_task_function.rs index 39b3e56..a7b0bd7 100644 --- a/crates/vlog_linter/src/rules/invalid_system_task_function.rs +++ b/crates/vlog_linter/src/rules/invalid_system_task_function.rs @@ -1,6 +1,7 @@ //! `invalid-system-task-function` — system tasks nothing should still call. use crate::context::LintContext; +use crate::options::{OptionDefault, OptionKind, OptionSpec}; use crate::registry::Rule; use crate::severity::Severity; use crate::violation::Violation; @@ -11,6 +12,26 @@ pub struct InvalidSystemTaskFunction; const NAME: &str = "invalid-system-task-function"; +/// The list, as an option — Verible hard-codes it in the source file it calls +/// `forbidden-symbol`, which is this rule under its implementation's name. +const OPTIONS: &[OptionSpec] = &[OptionSpec { + name: "symbols", + kind: OptionKind::List, + default: OptionDefault::List(&[ + "$psprintf", + "$random", + "$srandom", + "$dist_chi_square", + "$dist_erlang", + "$dist_exponential", + "$dist_normal", + "$dist_poisson", + "$dist_t", + "$dist_uniform", + ]), + doc: "system task and function names nothing may call, `$` included", +}]; + /// The forbidden names and what to write instead — Verible's list /// (`invalid-system-task-function`), name for name. /// @@ -46,6 +67,10 @@ impl Rule for InvalidSystemTaskFunction { Severity::Warning } + fn options(&self) -> &'static [OptionSpec] { + OPTIONS + } + fn doc(&self) -> &'static str { "`$random`, `$srandom` and the `$dist_*` family all draw from one \ global generator, so adding a call anywhere in a testbench reshuffles \ @@ -55,23 +80,32 @@ impl Rule for InvalidSystemTaskFunction { vendor spelling of the standard `$sformatf` and is not portable. \ Verible's `invalid-system-task-function` (\"Checks that no forbidden \ system tasks or functions are used.\", enabled by default) forbids \ - exactly this list, and lucisv names the replacement in the message. \ + exactly this list, and lucisv names the replacement in the message.\n\n\ + **There is no separate `forbidden-symbol` rule**, here or in Verible: \ + `forbidden-symbol` is the name of the *source file* Verible \ + implements this rule in, and the rule it registers is this one. The \ + list Verible hard-codes there is lucisv's `symbols` option, so a \ + project that wants `$stop` or a vendor task on it writes it down \ + instead of getting a second rule that would fire twice on \ + `$psprintf`. A name the default list knows is reported with its \ + replacement; one a project adds is reported without, because only \ + the project knows what to use instead.\n\n\ No automatic fix: `$random` and `$urandom` return different value \ streams, so swapping them changes what the test does." } fn check(&self, ctx: &LintContext) -> Vec { + let forbidden = ctx.option_list(NAME, "symbols"); ctx.tokens() .iter() .filter(|token| token.kind == TokenKind::SystemIdent) .filter_map(|token| { - let (name, instead) = - FORBIDDEN.iter().find(|(name, _)| *name == token.text.as_str())?; - Some(Violation::new( - NAME, - format!("`{name}` is forbidden; use `{instead}`"), - token.span, - )) + let name = forbidden.iter().find(|name| *name == &token.text)?; + let message = match FORBIDDEN.iter().find(|(known, _)| known == name) { + Some((_, instead)) => format!("`{name}` is forbidden; use `{instead}`"), + None => format!("`{name}` is forbidden by this project's settings"), + }; + Some(Violation::new(NAME, message, token.span)) }) .collect() } @@ -129,4 +163,36 @@ mod tests { let src = "module m;\n initial $display(\"call $random here\");\nendmodule\n"; assert!(violations(src).is_empty()); } + + /// The `symbols` option is `forbidden-symbol`'s list, folded into the one + /// rule Verible actually registers. + #[test] + fn the_option_replaces_the_list() { + use crate::options::RuleOptions; + let src = "module m;\n initial begin\n a = $random();\n $stop;\n end\nendmodule\n"; + assert_eq!(violations(src).len(), 1, "the default list has `$random` and not `$stop`"); + + let mut options = RuleOptions::new(); + options.set_raw(NAME, "symbols", "[\"$stop\"]").expect("accepted"); + let found = + InvalidSystemTaskFunction.check(&LintContext::new(src, None).with_options(&options)); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("$stop"), "{}", found[0].message); + assert!( + found[0].message.contains("this project's settings"), + "a name with no known replacement says so: {}", + found[0].message + ); + } + + #[test] + fn an_empty_list_reports_nothing() { + use crate::options::RuleOptions; + let src = "module m;\n initial a = $random();\nendmodule\n"; + let mut options = RuleOptions::new(); + options.set_raw(NAME, "symbols", "[]").expect("accepted"); + assert!(InvalidSystemTaskFunction + .check(&LintContext::new(src, None).with_options(&options)) + .is_empty()); + } } diff --git a/crates/vlog_linter/src/rules/legacy_generate_region.rs b/crates/vlog_linter/src/rules/legacy_generate_region.rs new file mode 100644 index 0000000..d452f9f --- /dev/null +++ b/crates/vlog_linter/src/rules/legacy_generate_region.rs @@ -0,0 +1,104 @@ +//! `legacy-generate-region` — the `generate … endgenerate` wrapper. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_items; +use vlog_parser::ast::ItemKind; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct LegacyGenerateRegion; + +const NAME: &str = "legacy-generate-region"; + +impl Rule for LegacyGenerateRegion { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "write generate constructs without a `generate … endgenerate` region" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn default_on(&self) -> bool { + false + } + + fn doc(&self) -> &'static str { + "Verilog-2001 required generate constructs to sit inside a \ + `generate … endgenerate` region. SystemVerilog does not (IEEE 1800 \ + §27.3): an `if`, `for` or `case` generate is a module item like any \ + other, and the wrapper adds a level of indentation, a keyword pair to \ + match and nothing else. Verible's `legacy-generate-region` (\"Checks \ + that there are no generate regions.\", **disabled** by default) is \ + the same rule and lucisv ships it off for the same reason: a codebase \ + that must still compile as Verilog-2001 needs the region, and only \ + the project knows which one it is.\n\n\ + No automatic fix. Deleting the two keywords is a whole-region edit \ + that re-indents everything between them, which is the formatter's \ + job and not a lint fix's." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_items(ctx.file(), &mut |item| { + if !matches!(item.kind, ItemKind::GenerateRegion { .. }) { + return; + } + // Point at the `generate` keyword, which is where the region opens. + let kw = TextRange::new(item.span.start, item.span.start + 8); + out.push(Violation::new( + NAME, + "`generate … endgenerate` region is not needed in SystemVerilog", + kw, + )); + }); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + LegacyGenerateRegion.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_region_and_points_at_its_keyword() { + let src = "module m;\n generate\n if (A) begin : g\n wire a;\n end\n \ + endgenerate\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "generate"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn a_generate_construct_without_the_wrapper_is_what_the_rule_wants() { + let src = "module m;\n if (A) begin : g\n wire a;\n end\n\ + \x20 for (genvar i = 0; i < 2; i++) begin : l\n wire b;\n end\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn every_region_of_a_file_is_reported() { + let src = "module a;\n generate\n endgenerate\nendmodule\n\ + module b;\n generate\n endgenerate\nendmodule\n"; + assert_eq!(violations(src).len(), 2); + } + + #[test] + fn a_nested_region_is_reported_too() { + let src = "module m;\n generate\n if (A) begin : g\n generate\n \ + endgenerate\n end\n endgenerate\nendmodule\n"; + assert_eq!(violations(src).len(), 2, "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/legacy_genvar_declaration.rs b/crates/vlog_linter/src/rules/legacy_genvar_declaration.rs new file mode 100644 index 0000000..ee61327 --- /dev/null +++ b/crates/vlog_linter/src/rules/legacy_genvar_declaration.rs @@ -0,0 +1,106 @@ +//! `legacy-genvar-declaration` — declare the loop variable in the `for` header. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_items; +use vlog_parser::ast::ItemKind; + +/// See [`Rule::doc`]. +pub struct LegacyGenvarDeclaration; + +const NAME: &str = "legacy-genvar-declaration"; + +impl Rule for LegacyGenvarDeclaration { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "declare a genvar in the `for` header, not in a separate statement" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn default_on(&self) -> bool { + false + } + + fn doc(&self) -> &'static str { + "Verilog-2001 made a `genvar` a module-scope declaration, so a loop \ + variable outlived the loop that used it and two loops sharing one \ + `genvar i;` read as if they shared a variable. SystemVerilog lets the \ + header declare it — `for (genvar i = 0; i < N; i++)` — which scopes \ + the name to the loop and makes each loop's variable its own (IEEE \ + 1800 §27.4). Verible's `legacy-genvar-declaration` (\"Checks that \ + there are no separate `genvar` declarations.\", **disabled** by \ + default) is the same rule, and lucisv ships it off for the same \ + reason: a Verilog-2001 codebase has no other spelling available.\n\n\ + No automatic fix: moving the declaration means editing every `for` \ + header that used it, and only the author knows which ones those are." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_items(ctx.file(), &mut |item| { + let ItemKind::Genvar(names) = &item.kind else { return }; + for name in names { + out.push(Violation::new( + NAME, + format!( + "genvar `{}` is declared outside a `for` header; write \ + `for (genvar {} = …)`", + name.text, name.text + ), + name.span, + )); + } + }); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + LegacyGenvarDeclaration.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_separate_declaration_and_points_at_the_name() { + let src = "module m;\n genvar i;\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "i"); + assert!(found[0].message.contains("`i`"), "{}", found[0].message); + assert!(found[0].fix.is_none()); + } + + #[test] + fn every_name_of_one_declaration_is_reported() { + assert_eq!(violations("module m;\n genvar i, j, k;\nendmodule\n").len(), 3); + } + + #[test] + fn a_header_declaration_is_what_the_rule_wants() { + let src = "module m;\n for (genvar i = 0; i < 2; i++) begin : g\n wire a;\n end\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn an_ordinary_variable_is_not_a_genvar() { + assert!(violations("module m;\n integer i;\n int j;\nendmodule\n").is_empty()); + } + + #[test] + fn a_declaration_inside_a_generate_region_is_reached() { + let src = "module m;\n generate\n genvar i;\n endgenerate\nendmodule\n"; + assert_eq!(violations(src).len(), 1); + } +} diff --git a/crates/vlog_linter/src/rules/macro_string_concatenation.rs b/crates/vlog_linter/src/rules/macro_string_concatenation.rs new file mode 100644 index 0000000..1612237 --- /dev/null +++ b/crates/vlog_linter/src/rules/macro_string_concatenation.rs @@ -0,0 +1,161 @@ +//! `macro-string-concatenation` — `` `` `` inside a plain string does nothing. + +use crate::context::LintContext; +use crate::preproc::directive_word; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct MacroStringConcatenation; + +const NAME: &str = "macro-string-concatenation"; + +impl Rule for MacroStringConcatenation { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "do not write the `` `` `` concatenation operator inside a plain string" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn default_on(&self) -> bool { + false + } + + fn doc(&self) -> &'static str { + "Inside a `` `define `` body, `` `` `` glues two tokens together and \ + `` `\" `` opens a string the preprocessor still looks inside \ + (IEEE 1800 §22.5.1). Written inside an *ordinary* `\"…\"` string the \ + operator is not an operator at all — the preprocessor does not \ + expand anything in a plain string literal, so the two backticks end \ + up in the output text and the macro silently produces `` a``b `` \ + where the author expected `ab`. Verible's \ + `macro-string-concatenation` (\"Concatenation will not be evaluated \ + here. Use `\\\"...`\\\" instead.\", **disabled** by default) reports \ + the same shape, and lucisv ships it off for the same reason: it is a \ + narrow mistake, and a project with no macro-built strings never meets \ + it.\n\n\ + Only a `` `define `` body is scanned, and only its plain string \ + literals — a `` `\"…`\" `` region is exactly the correct spelling and \ + is skipped. No automatic fix: turning `\"…\"` into `` `\"…`\" `` \ + changes what the macro expands to, which is the repair but not one a \ + linter should make unasked." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + for token in ctx.tokens() { + if directive_word(token) != Some("define") { + continue; + } + for offset in concatenations_in_plain_strings(&token.text) { + let start = token.span.start + offset as u32; + out.push(Violation::new( + NAME, + "token concatenation inside a plain string literal is not evaluated; \ + write the string as `\"...`\"", + TextRange::new(start, start + 2), + )); + } + } + out + } +} + +/// Byte offsets of every `` `` `` written inside a plain `"…"` literal of +/// `text`, in source order. +/// +/// A `` `"…`" `` region — the spelling that *does* work — is skipped whole, +/// which is what keeps the correct form from being reported as the mistake. +fn concatenations_in_plain_strings(text: &str) -> Vec { + let bytes = text.as_bytes(); + let mut out = Vec::new(); + let mut i = 0usize; + while i < bytes.len() { + if bytes[i] == b'`' && bytes.get(i + 1) == Some(&b'"') { + i = match find(bytes, i + 2, b"`\"") { + Some(end) => end + 2, + None => break, + }; + continue; + } + if bytes[i] != b'"' { + i += 1; + continue; + } + let mut j = i + 1; + while j < bytes.len() && bytes[j] != b'"' { + if bytes[j] == b'\\' { + j += 1; + } + if bytes.get(j) == Some(&b'`') && bytes.get(j + 1) == Some(&b'`') { + out.push(j); + j += 1; + } + j += 1; + } + i = j + 1; + } + out +} + +/// The offset of the next `needle` at or after `from`. +fn find(bytes: &[u8], from: usize, needle: &[u8]) -> Option { + (from..bytes.len().saturating_sub(needle.len() - 1)) + .find(|&i| &bytes[i..i + needle.len()] == needle) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + MacroStringConcatenation.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_the_operator_and_underlines_it() { + let src = "`define GLUE(a, b) $display(\"a``b\")\nmodule m;\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "``"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn the_macro_quoted_spelling_is_the_correct_one() { + let src = "`define GLUE(a, b) $display(`\"a``b`\")\nmodule m;\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_define_with_no_string_is_silent() { + let src = "`define GLUE(a, b) a``b\nmodule m;\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_plain_string_outside_a_define_is_not_this_rules_business() { + let src = "module m;\n initial $display(\"a``b\");\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn every_occurrence_of_one_define_is_reported() { + let src = "`define G(a, b, c) $display(\"a``b\", \"b``c\")\nmodule m;\nendmodule\n"; + assert_eq!(violations(src).len(), 2, "{:?}", violations(src)); + } + + #[test] + fn an_escaped_quote_does_not_end_the_string_early() { + let src = "`define G(a) $display(\"x\\\"y``z\")\nmodule m;\nendmodule\n"; + assert_eq!(violations(src).len(), 1, "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/mod.rs b/crates/vlog_linter/src/rules/mod.rs index d76e582..3417e33 100644 --- a/crates/vlog_linter/src/rules/mod.rs +++ b/crates/vlog_linter/src/rules/mod.rs @@ -13,24 +13,36 @@ pub mod always_ff_non_blocking; pub mod banned_declared_name_patterns; pub mod case_missing_default; pub mod constraint_name_style; +pub mod create_object_name_match; +pub mod dff_name_style; +pub mod disable_statement; pub mod duplicate_declaration; pub mod empty_item; +pub mod endif_comment; pub mod enum_name_style; pub mod explicit_begin; +pub mod explicit_function_lifetime; pub mod explicit_function_task_parameter_type; pub mod explicit_parameter_storage_type; +pub mod explicit_task_lifetime; pub mod forbid_consecutive_null_statements; pub mod forbid_defparam; +pub mod forbid_line_continuations; pub mod forbid_negative_array_dim; +pub mod forbidden_macro; 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 legacy_generate_region; +pub mod legacy_genvar_declaration; pub mod line_length; pub mod macro_name_style; +pub mod macro_string_concatenation; pub mod mismatched_labels; +pub mod module_begin_block; pub mod module_filename; pub mod module_name_style; pub mod module_parameter; @@ -38,6 +50,7 @@ pub mod module_port; pub mod multiply_driven; pub mod no_tabs; pub mod no_trailing_whitespace; +pub mod numeric_format_string_style; pub mod one_module_per_file; pub mod package_filename; pub mod packed_dimensions_range_ordering; @@ -45,9 +58,12 @@ pub mod parameter_name_style; pub mod parameter_type_name_style; pub mod plusarg_assignment; pub mod port_name_suffix; +pub mod positive_meaning_parameter_name; pub mod posix_eof; +pub mod proper_parameter_declaration; pub mod signal_name_style; pub mod struct_union_name_style; +pub mod suggest_parentheses; pub mod suspicious_semicolon; pub mod truncated_numeric_literal; pub mod typedef_enums; @@ -57,7 +73,10 @@ pub mod undersized_binary_literal; pub mod undriven_net; pub mod unknown_parameter; pub mod unknown_port; +pub mod unpacked_dimensions_range_ordering; pub mod unused_signal; pub mod unused_waiver; +pub mod uvm_macro_semicolon; +pub mod v2001_generate_begin; pub mod void_cast; pub mod wire_reg_mixup; diff --git a/crates/vlog_linter/src/rules/module_begin_block.rs b/crates/vlog_linter/src/rules/module_begin_block.rs new file mode 100644 index 0000000..54e6ce8 --- /dev/null +++ b/crates/vlog_linter/src/rules/module_begin_block.rs @@ -0,0 +1,165 @@ +//! `module-begin-block` — no `begin`/`end` block at module scope. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::ast::{Item, ItemKind, RawText}; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct ModuleBeginBlock; + +const NAME: &str = "module-begin-block"; + +impl Rule for ModuleBeginBlock { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "do not write a `begin`/`end` block at module scope" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn doc(&self) -> &'static str { + "A `begin … end` written straight into a module body is not a module \ + item: IEEE 1800 §23.2.1 lists what may stand there, and a sequential \ + block is not on the list. Tools that accept it treat it as an \ + unnamed generate block, so the declarations inside it land in an \ + invented scope (`genblk1.x`) and every hierarchical path written \ + against them is wrong. Verible's `module-begin-block` (\"Checks that \ + there are no begin-end blocks declared at the module level.\", \ + enabled by default) is the same rule and the same default.\n\n\ + lucisv's **parser rejects** the construct rather than recovering it \ + as a block, so what this rule reads is the error leaf error recovery \ + left at module scope whose first token is `begin`. The finding is \ + exact — no legal module item starts with that keyword — but the rest \ + of the module is lost to recovery, so a file with one of these \ + reports little else. No automatic fix: whether the block should \ + become a generate block, an `always` or nothing at all is the \ + author's to decide." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + for item in &ctx.file().items { + module_items(item, &mut |inner| { + if let Some(span) = begin_block(inner) { + out.push(Violation::new( + NAME, + "`begin`/`end` block at module scope; a module item belongs here", + span, + )); + } + }); + } + out + } +} + +/// The `begin` keyword of an error leaf that is a `begin … end` block, or +/// `None` for any other leaf. +/// +/// Shared with `v2001-generate-begin`, which asks the same question one scope +/// further in: the two rules must agree about what a stray `begin` looks like, +/// and one reading is how that is guaranteed. +pub(crate) fn begin_block(item: &Item) -> Option { + let ItemKind::Error(raw) = &item.kind else { return None }; + if !first_word_is_begin(raw) { + return None; + } + Some(TextRange::new(raw.span.start, raw.span.start + 5)) +} + +/// True when the leaf's first token is exactly the keyword `begin`. +fn first_word_is_begin(raw: &RawText) -> bool { + let rest = match raw.text.strip_prefix("begin") { + Some(rest) => rest, + None => return false, + }; + // `beginning` is an identifier, not the keyword. + !rest.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$') +} + +/// Calls `f` on every item written directly in a module, interface or program +/// body — nested units included, generate constructs deliberately not, since +/// a `begin` inside one of those is `v2001-generate-begin`'s business. +fn module_items(item: &Item, f: &mut dyn FnMut(&Item)) { + match &item.kind { + ItemKind::Module(module) => { + for inner in &module.items { + f(inner); + module_items(inner, f); + } + } + ItemKind::Package { items, .. } => { + for inner in items { + module_items(inner, f); + } + } + _ => {} + } +} + +/// Whether `file` holds a module at all — used by the tests below only. +#[cfg(test)] +fn has_module(file: &vlog_parser::ast::SourceFile) -> bool { + file.items.iter().any(|item| matches!(item.kind, ItemKind::Module(_))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + ModuleBeginBlock.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_module_scope_block_and_points_at_its_begin() { + let src = "module m;\n begin\n wire a;\n end\nendmodule\n"; + let ctx = LintContext::new(src, None); + assert!(has_module(ctx.file()), "the probe needs the module to survive recovery"); + 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 an_ordinary_module_body_is_silent() { + let src = "module m;\n\ + \x20 wire a;\n\ + \x20 initial begin\n a = 1;\n end\n\ + \x20 always_comb begin\n b = a;\n end\n\ + \x20 if (A) begin : g\n wire c;\n end\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_block_inside_a_generate_region_belongs_to_the_other_rule() { + let src = "module m;\n generate\n begin : b\n wire a;\n end\n \ + endgenerate\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn an_identifier_that_starts_with_begin_is_not_the_keyword() { + // The error leaf of an unparsable item starting with `beginning` must + // not be read as a block. + let src = "module m;\n beginning @@@;\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_file_that_parses_cleanly_has_nothing_to_report() { + let src = "module m;\n wire a;\nendmodule\n"; + assert!(LintContext::new(src, None).parsed_cleanly()); + assert!(violations(src).is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/numeric_format_string_style.rs b/crates/vlog_linter/src/rules/numeric_format_string_style.rs new file mode 100644 index 0000000..5476a78 --- /dev/null +++ b/crates/vlog_linter/src/rules/numeric_format_string_style.rs @@ -0,0 +1,250 @@ +//! `numeric-format-string-style` — a radix prefix must match its specifier. + +use crate::context::LintContext; +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 NumericFormatStringStyle; + +const NAME: &str = "numeric-format-string-style"; + +/// The base a prefix or a format specifier names. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Radix { + Binary, + Hex, + Decimal, +} + +impl Radix { + /// The base this letter names, or `None` for a letter that names none. + fn of(letter: char) -> Option { + match letter { + 'b' | 'B' => Some(Radix::Binary), + 'h' | 'H' | 'x' | 'X' => Some(Radix::Hex), + 'd' | 'D' => Some(Radix::Decimal), + _ => None, + } + } + + /// The word a message calls this base. + fn word(self) -> &'static str { + match self { + Radix::Binary => "binary", + Radix::Hex => "hexadecimal", + Radix::Decimal => "decimal", + } + } +} + +impl Rule for NumericFormatStringStyle { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "give a numeric format specifier the radix prefix that matches it" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn default_on(&self) -> bool { + false + } + + fn doc(&self) -> &'static str { + "A log line that prints `addr = 0x1010` when the value was formatted \ + with `%b` has told the reader a lie that costs an hour: they read the \ + number in the base the prefix claims. The convention is to write the \ + prefix that matches — `0x%0h`, `'b%0b` — or to write no prefix at \ + all, and to give a decimal number none, because `0d` is not a prefix \ + anyone reads. Verible's `numeric-format-string-style` (\"Checks that \ + string literals with numeric format specifiers have proper \ + prefixes.\", **disabled** by default) reports exactly the mismatch, \ + and lucisv ships it off for the same reason: it is a house \ + convention, not a defect.\n\n\ + A specifier with **no prefix is always accepted** — `\"%0h\"` and \ + `\"%d\"` are clean. What is reported is a `0`- or `'`-introduced \ + radix prefix immediately before the `%` that names a different base \ + (`\"0x%0b\"`, `\"'b%0d\"`), and any prefix at all before a decimal \ + specifier (`\"0d%0d\"`). Only real string literals are scanned: a \ + string written inside a macro invocation is part of that \ + invocation's one token and is not seen here. No automatic fix — \ + which half is wrong, the prefix or the specifier, is the author's to \ + say." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + for token in ctx.tokens().iter().filter(|t| t.kind == TokenKind::String) { + for bad in mismatches(&token.text) { + let start = token.span.start + bad.start as u32; + let end = token.span.start + bad.end as u32; + out.push(Violation::new( + NAME, + format!( + "`{}` prints a {} value after a {} prefix", + bad.text, + bad.specifier.word(), + match bad.prefix { + Some(prefix) => prefix.word(), + None => "radix", + } + ), + TextRange::new(start, end), + )); + } + } + out + } +} + +/// One badly prefixed specifier: where it is, what it says, and what the +/// prefix in front of it claimed. +struct Mismatch { + start: usize, + end: usize, + text: String, + prefix: Option, + specifier: Radix, +} + +/// Every prefix/specifier mismatch of one string literal, in source order. +fn mismatches(text: &str) -> Vec { + let bytes = text.as_bytes(); + let mut out = Vec::new(); + let mut i = 0usize; + while i < bytes.len() { + if bytes[i] != b'%' { + i += 1; + continue; + } + // `%%` is a literal per cent, not a specifier. + if bytes.get(i + 1) == Some(&b'%') { + i += 2; + continue; + } + let mut j = i + 1; + while bytes.get(j).is_some_and(u8::is_ascii_digit) { + j += 1; + } + let Some(specifier) = bytes.get(j).map(|&b| b as char).and_then(Radix::of) else { + i = j.max(i + 1); + continue; + }; + let prefix = prefix_before(bytes, i); + let wrong = match (prefix, specifier) { + (Some(_), Radix::Decimal) => true, + (Some(prefix), specifier) => prefix != specifier, + (None, _) => false, + }; + if wrong { + let start = if prefix.is_some() { i - 2 } else { i }; + out.push(Mismatch { + start, + end: j + 1, + text: text[start..j + 1].to_string(), + prefix, + specifier, + }); + } + i = j + 1; + } + out +} + +/// The radix a `0x` / `'b`-shaped prefix immediately before `at` claims. +fn prefix_before(bytes: &[u8], at: usize) -> Option { + if at < 2 { + return None; + } + if !matches!(bytes[at - 2], b'0' | b'\'') { + return None; + } + Radix::of(bytes[at - 1] as char) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + NumericFormatStringStyle.check(&LintContext::new(src, None)) + } + + fn display(literal: &str) -> String { + format!("module m;\n initial $display({literal}, v);\nendmodule\n") + } + + #[test] + fn flags_a_mismatched_prefix_and_underlines_prefix_and_specifier() { + let src = display("\"0x%0b\""); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "0x%0b"); + assert!(found[0].fix.is_none()); + } + + /// Verible's own accepted list, literal for literal. + #[test] + fn a_matching_or_absent_prefix_is_accepted() { + for literal in [ + "\"0x%0x\"", + "\"'h%0h\"", + "\"'h%h\"", + "\"0h%h\"", + "\"%0x\"", + "\"%h\"", + "\"%x\"", + "\"0b%0b\"", + "\"'b%0b\"", + "\"%0b\"", + "\"%0d\"", + "\"0x%0x, %d\"", + "\"0x%0x (bin: 'b%b, dec: %d)\"", + ] { + let src = display(literal); + assert!(violations(&src).is_empty(), "{literal}: {:?}", violations(&src)); + } + } + + /// Verible's own rejected list, literal for literal. + #[test] + fn every_mismatch_verible_names_is_reported() { + for literal in [ + "\"0b%0x\"", + "\"'b%0x\"", + "\"0x%0b\"", + "\"'h%0b\"", + "\"0x%0d\"", + "\"'h%0d\"", + "\"0b%0d\"", + "\"'b%0d\"", + "\"0d%0d\"", + "\"'d%0d\"", + ] { + let src = display(literal); + assert_eq!(violations(&src).len(), 1, "{literal}: {:?}", violations(&src)); + } + } + + #[test] + fn a_non_numeric_specifier_and_a_literal_percent_are_ignored() { + for literal in ["\"%s\"", "\"%0t\"", "\"%m\"", "\"100%% done\"", "\"0x%s\""] { + let src = display(literal); + assert!(violations(&src).is_empty(), "{literal}: {:?}", violations(&src)); + } + } + + #[test] + fn each_specifier_of_one_string_is_judged_on_its_own() { + let src = display("\"0x%0b and 0b%0h and %d\""); + assert_eq!(violations(&src).len(), 2, "{:?}", violations(&src)); + } +} diff --git a/crates/vlog_linter/src/rules/positive_meaning_parameter_name.rs b/crates/vlog_linter/src/rules/positive_meaning_parameter_name.rs new file mode 100644 index 0000000..1a3198e --- /dev/null +++ b/crates/vlog_linter/src/rules/positive_meaning_parameter_name.rs @@ -0,0 +1,134 @@ +//! `positive-meaning-parameter-name` — no `disable`-prefixed parameter. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::{walk_all_stmts, walk_items, walk_param_ports}; +use vlog_parser::ast::{ItemKind, StmtKind}; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct PositiveMeaningParameterName; + +const NAME: &str = "positive-meaning-parameter-name"; + +/// The prefix a parameter must not start with, compared case-insensitively. +const FORBIDDEN_PREFIX: &str = "disable"; + +impl Rule for PositiveMeaningParameterName { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "name a parameter for what it enables, not for what it disables" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn doc(&self) -> &'static str { + "A negatively named parameter forces every use of it to be read \ + twice: `if (!DisableEcc)` is a double negative, and a default of \ + `DisableEcc = 0` means \"ECC is on\", which nobody reads correctly at \ + speed. Naming the positive meaning — `EnableEcc`, `EccEnabled` — \ + makes each use say what it does. Verible's \ + `positive-meaning-parameter-name` (\"Checks that no parameter name \ + starts with 'disable', using positive naming is recommended.\", \ + enabled by default) is the same rule and the same default; the \ + comparison is case-insensitive there and here, so `DISABLE_X` and \ + `disable_x` are both reported.\n\n\ + Every parameter is judged, in a formal parameter list and in a body \ + declaration alike, `localparam` included. No automatic fix: \ + inverting a parameter means inverting every use of it and its \ + default, which is a refactor, not a repair." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + let mut judge = |name: &str, span: TextRange| { + if !starts_with_disable(name) { + return; + } + out.push(Violation::new( + NAME, + format!( + "parameter `{name}` is named for what it disables; name the positive meaning" + ), + span, + )); + }; + walk_param_ports(ctx.file(), &mut |port| judge(&port.name, port.name_span)); + walk_items(ctx.file(), &mut |item| { + let ItemKind::ParamDecl(decl) = &item.kind else { return }; + for declarator in &decl.declarators { + judge(&declarator.name, declarator.name_span); + } + }); + walk_all_stmts(ctx.file(), &mut |stmt| { + let StmtKind::ParamDecl(decl) = &stmt.kind else { return }; + for declarator in &decl.declarators { + judge(&declarator.name, declarator.name_span); + } + }); + out + } +} + +/// True when `name` begins with `disable`, in any case. +fn starts_with_disable(name: &str) -> bool { + name.len() >= FORBIDDEN_PREFIX.len() + && name[..FORBIDDEN_PREFIX.len()].eq_ignore_ascii_case(FORBIDDEN_PREFIX) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + PositiveMeaningParameterName.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_formal_parameter_and_points_at_its_name() { + let src = "module m #(parameter int DisableEcc = 0) ();\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "DisableEcc"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn the_prefix_is_matched_in_any_case() { + for name in ["disable_ecc", "DISABLE_ECC", "DisableEcc", "dIsAbLe"] { + let src = format!("module m;\n localparam int {name} = 0;\nendmodule\n"); + assert_eq!(violations(&src).len(), 1, "{name}"); + } + } + + #[test] + fn a_positive_name_is_what_the_rule_wants() { + for name in ["EnableEcc", "EccEnabled", "Width", "Dis", "NotDisabled", "UnDisable"] { + let src = format!("module m;\n localparam int {name} = 0;\nendmodule\n"); + assert!(violations(&src).is_empty(), "{name}: {:?}", violations(&src)); + } + } + + #[test] + fn every_place_a_parameter_is_written_is_reached() { + let src = "module m #(parameter int DisableA = 0) ();\n\ + \x20 localparam int DisableB = 0;\n\ + \x20 function automatic int f();\n parameter int DisableC = 0;\n \ + return DisableC;\n endfunction\n\ + endmodule\n\ + class c #(parameter int DisableD = 0);\nendclass\n"; + assert_eq!(violations(src).len(), 4, "{:?}", violations(src)); + } + + #[test] + fn an_ordinary_signal_is_not_a_parameter() { + assert!(violations("module m;\n wire disable_ecc;\nendmodule\n").is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/proper_parameter_declaration.rs b/crates/vlog_linter/src/rules/proper_parameter_declaration.rs new file mode 100644 index 0000000..3c9db6a --- /dev/null +++ b/crates/vlog_linter/src/rules/proper_parameter_declaration.rs @@ -0,0 +1,196 @@ +//! `proper-parameter-declaration` — `parameter` in a header, `localparam` in a body. + +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_items_scoped, ItemScope}; +use vlog_parser::ast::ItemKind; + +/// See [`Rule::doc`]. +pub struct ProperParameterDeclaration; + +const NAME: &str = "proper-parameter-declaration"; + +/// Verible's two options, spelled and defaulted as Verible spells them. +const OPTIONS: &[OptionSpec] = &[ + OptionSpec { + name: "package_allow_parameter", + kind: OptionKind::Bool, + default: OptionDefault::Bool(false), + doc: "accept `parameter` in a package body", + }, + OptionSpec { + name: "package_allow_localparam", + kind: OptionKind::Bool, + default: OptionDefault::Bool(true), + doc: "accept `localparam` in a package body", + }, +]; + +impl Rule for ProperParameterDeclaration { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "declare `parameter` only in a formal parameter list and `localparam` only in a body" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn default_on(&self) -> bool { + false + } + + fn options(&self) -> &'static [OptionSpec] { + OPTIONS + } + + fn doc(&self) -> &'static str { + "A `parameter` is what an instantiation may override, so it belongs \ + in the `#( … )` a caller can see. Written in a module *body* it is \ + still overridable — by `defparam`, or by a hierarchical override — \ + which means a value the reader believes is fixed can change from \ + outside with nothing at the declaration to say so. `localparam` is \ + the spelling for a constant that is nobody's business but the \ + module's. Verible's `proper-parameter-declaration` (\"Checks that \ + `parameter` declarations are in formal parameter lists and \ + `localparam` in modules/classes/packages.\", **disabled** by \ + default) is the same rule and the same default, with the same two \ + options: `package_allow_parameter` (false) and \ + `package_allow_localparam` (true).\n\n\ + A **formal parameter list is never judged** — `#(parameter int W = \ + 8)` and `#(localparam int X = 2*W)` are both fine there. What is \ + judged is a body declaration: `parameter` anywhere is wrong (in a \ + package, unless `package_allow_parameter`), and `localparam` is \ + right in a module, interface, program or class body, wrong at file \ + scope, and in a package answers to `package_allow_localparam`. Only \ + item-scope declarations are read; a `parameter` written among a \ + subroutine's statements is left to the language. No automatic fix: \ + `parameter` → `localparam` removes an override an instantiation may \ + be relying on." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let allow_parameter = ctx.option_bool(NAME, "package_allow_parameter"); + let allow_localparam = ctx.option_bool(NAME, "package_allow_localparam"); + let mut out = Vec::new(); + walk_items_scoped(ctx.file(), &mut |scope, item| { + let ItemKind::ParamDecl(decl) = &item.kind else { return }; + let Some(first) = decl.declarators.first() else { return }; + let Some(message) = complaint(&decl.kw, scope, allow_parameter, allow_localparam) + else { + return; + }; + out.push(Violation::new(NAME, message, first.name_span)); + }); + out + } +} + +/// What is wrong with this keyword in this scope, or `None` when nothing is. +fn complaint( + kw: &str, + scope: ItemScope, + allow_parameter: bool, + allow_localparam: bool, +) -> Option { + match (kw, scope) { + ("parameter", ItemScope::Package) if allow_parameter => None, + ("parameter", _) => Some( + "`parameter` belongs in a formal parameter list; write `localparam` for a \ + body constant" + .to_string(), + ), + ("localparam", ItemScope::Package) if allow_localparam => None, + ("localparam", ItemScope::Package) => Some( + "`localparam` is not accepted in a package body by this project's settings".to_string(), + ), + ("localparam", ItemScope::File) => { + Some("`localparam` belongs in a module, interface, program or class body".to_string()) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::options::RuleOptions; + + fn violations(src: &str) -> Vec { + ProperParameterDeclaration.check(&LintContext::new(src, None)) + } + + fn with(src: &str, key: &str, raw: &str) -> Vec { + let mut options = RuleOptions::new(); + options.set_raw(NAME, key, raw).expect("accepted"); + ProperParameterDeclaration.check(&LintContext::new(src, None).with_options(&options)) + } + + #[test] + fn flags_a_parameter_in_a_module_body_and_points_at_its_name() { + let src = "module m;\n parameter int Bar = 1;\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "Bar"); + assert!(found[0].fix.is_none()); + } + + /// Verible's own accepted list, snippet for snippet. + #[test] + fn the_shapes_verible_accepts_are_accepted() { + for src in [ + "module foo; localparam int Bar = 1; endmodule\n", + "class foo; localparam int Bar = 1; endclass\n", + "package foo; localparam int Bar = 1; endpackage\n", + "module foo #(localparam int Bar = 1); endmodule\n", + "module foo #(parameter int Bar = 1); endmodule\n", + ] { + assert!(violations(src).is_empty(), "{src}: {:?}", violations(src)); + } + } + + /// Verible's own rejected list, snippet for snippet. + #[test] + fn the_shapes_verible_rejects_are_reported() { + for src in [ + "parameter int Foo = 1;\n", + "package foo; parameter int Bar = 1; endpackage\n", + "module foo; parameter int Bar = 1; endmodule\n", + "class foo; parameter int Bar = 1; endclass\n", + "package foo; class bar; parameter int HelloWorld = 1; endclass endpackage\n", + ] { + assert_eq!(violations(src).len(), 1, "{src}: {:?}", violations(src)); + } + } + + #[test] + fn package_allow_parameter_moves_the_line() { + let src = "package foo; parameter int Bar = 1; endpackage\n"; + assert_eq!(violations(src).len(), 1); + assert!(with(src, "package_allow_parameter", "true").is_empty()); + } + + #[test] + fn package_allow_localparam_moves_it_the_other_way() { + let src = "package foo; localparam int Bar = 1; endpackage\n"; + assert!(violations(src).is_empty()); + assert_eq!(with(src, "package_allow_localparam", "false").len(), 1); + } + + #[test] + fn a_localparam_at_file_scope_has_no_body_to_belong_to() { + assert_eq!(violations("localparam int Foo = 1;\n").len(), 1); + } + + #[test] + fn a_declaration_inside_a_generate_block_keeps_its_modules_scope() { + let src = "module m;\n if (A) begin : g\n localparam int X = 1;\n end\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/suggest_parentheses.rs b/crates/vlog_linter/src/rules/suggest_parentheses.rs new file mode 100644 index 0000000..3c35f2e --- /dev/null +++ b/crates/vlog_linter/src/rules/suggest_parentheses.rs @@ -0,0 +1,145 @@ +//! `suggest-parentheses` — parenthesize a ternary nested in a ternary. + +use crate::context::LintContext; +use crate::exprs::walk_exprs; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::{Fix, Violation}; +use vlog_parser::ast::{Expr, ExprKind}; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct SuggestParentheses; + +const NAME: &str = "suggest-parentheses"; + +impl Rule for SuggestParentheses { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "parenthesize a conditional written in the true-clause of another" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn fix(&self) -> Option { + Some(crate::violation::Applicability::Safe) + } + + fn doc(&self) -> &'static str { + "`a ? b ? c : d : e` is legal and means `a ? (b ? c : d) : e` — the \ + conditional operator is right-associative — but the reader has to \ + know that and then count colons to find which `:` closes which `?`. \ + Two characters remove the question. Verible's `suggest-parentheses` \ + (\"Recommend extra parentheses around subexpressions where it helps \ + readability.\", enabled by default) reports exactly this shape: a \ + condition expression standing, unparenthesized, in the true-clause of \ + another condition expression. lucisv reports the same shape and \ + nothing more — a ternary in the *false*-clause is where the language \ + already puts it, and every other mixed-precedence expression is left \ + alone, because a rule that guessed at operator combinations would \ + report far more than it explained.\n\n\ + The fix is **safe**: it writes a `(` and a `)` around the inner \ + conditional and changes no token, which is the meaning the language \ + already gives the expression." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_exprs(ctx.file(), &mut |expr| { + let ExprKind::Ternary { then, .. } = &expr.kind else { return }; + if !matches!(then.kind, ExprKind::Ternary { .. }) { + return; + } + out.push( + Violation::new( + NAME, + "conditional in the true-clause of another conditional; parenthesize it", + then.span, + ) + .with_fix(Fix::safe(parenthesize(then))), + ); + }); + out + } +} + +/// The two insertions that wrap `expr` in parentheses, touching nothing else. +fn parenthesize(expr: &Expr) -> Vec<(TextRange, String)> { + vec![ + (TextRange::new(expr.span.start, expr.span.start), "(".to_string()), + (TextRange::new(expr.span.end, expr.span.end), ")".to_string()), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::violation::apply_fixes; + + fn violations(src: &str) -> Vec { + SuggestParentheses.check(&LintContext::new(src, None)) + } + + fn assign(rhs: &str) -> String { + format!("module m;\n assign x = {rhs};\nendmodule\n") + } + + #[test] + fn flags_the_nested_true_clause_and_underlines_it() { + let src = assign("a ? b ? c : d : e"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "b ? c : d"); + } + + #[test] + fn the_fix_only_adds_parentheses() { + let src = assign("a ? b ? c : d : e"); + let fixed = apply_fixes(&src, &violations(&src), false); + assert_eq!(fixed.applied, 1); + assert_eq!(fixed.output, assign("a ? (b ? c : d) : e")); + // ... and the fixed text has nothing left to report. + assert!(violations(&fixed.output).is_empty()); + } + + #[test] + fn an_already_parenthesized_clause_is_clean() { + assert!(violations(&assign("a ? (b ? c : d) : e")).is_empty()); + } + + #[test] + fn a_conditional_in_the_false_clause_is_where_the_language_puts_it() { + assert!(violations(&assign("a ? b : c ? d : e")).is_empty()); + } + + #[test] + fn a_plain_conditional_is_clean() { + assert!(violations(&assign("a ? b : c")).is_empty()); + assert!(violations(&assign("a + b * c")).is_empty()); + } + + #[test] + fn a_conditional_condition_is_not_this_rules_business() { + // Verible reports the true-clause only; a `?:` used as the condition + // of another already needs its own parentheses to parse. + assert!(violations(&assign("(a ? b : c) ? d : e")).is_empty()); + } + + #[test] + fn three_deep_reports_each_nesting() { + let src = assign("a ? b ? c ? d : e : f : g"); + assert_eq!(violations(&src).len(), 2, "{:?}", violations(&src)); + } + + #[test] + fn a_conditional_written_anywhere_is_reached() { + let src = "module m #(parameter int P = a ? b ? 1 : 2 : 3) ();\n\ + \x20 initial begin\n y = c ? d ? 1 : 2 : 3;\n end\nendmodule\n"; + assert_eq!(violations(src).len(), 2, "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/unpacked_dimensions_range_ordering.rs b/crates/vlog_linter/src/rules/unpacked_dimensions_range_ordering.rs new file mode 100644 index 0000000..00bdb16 --- /dev/null +++ b/crates/vlog_linter/src/rules/unpacked_dimensions_range_ordering.rs @@ -0,0 +1,161 @@ +//! `unpacked-dimensions-range-ordering` — write an array's extent `[0:N-1]`. + +use crate::context::LintContext; +use crate::decls::{walk_dims, Packing}; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::ast::{DimKind, Expr, ExprKind}; + +/// See [`Rule::doc`]. +pub struct UnpackedDimensionsRangeOrdering; + +const NAME: &str = "unpacked-dimensions-range-ordering"; + +impl Rule for UnpackedDimensionsRangeOrdering { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "declare an unpacked dimension in increasing order, `[0:N-1]`" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn doc(&self) -> &'static str { + "An unpacked dimension is an *array*, and an array counts up: element \ + 0 first. `logic q [7:0]` declares the same eight elements as \ + `logic q [0:7]` but numbers them backwards, so `foreach (q[i])` \ + visits them in the opposite order to the one the declaration suggests \ + and every `for (i = 0; i < 8; i++)` written beside it reads the array \ + the other way round. Verible's \ + `unpacked-dimensions-range-ordering` (\"Checks that unpacked \ + dimension ranges are declared in big-endian order `[0:N-1]`.\", \ + enabled by default) is the same rule and the same default — and it \ + is the mirror image of `packed-dimensions-range-ordering`, which \ + wants a *vector*'s width the other way, `[N-1:0]`.\n\n\ + Only a range is judged. A sized extent (`logic q [8]`), a dynamic \ + (`[]`), an associative (`[*]`, `[key_t]`) and a queue are not \ + ranges and are left alone. A range is flagged when both bounds are \ + integer literals and the left one is larger, and when the right one \ + is a literal `0` and the left is anything else (`[N-1:0]`) — every \ + other shape is two symbolic bounds lucisv does not evaluate. No \ + automatic fix: reversing a range reverses every use of it." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_dims(ctx.file(), &mut |packing, dim| { + if packing != Packing::Unpacked { + return; + } + let DimKind::Range { a, b: Some(b) } = &dim.kind else { return }; + if !descending(a, b) { + return; + } + out.push(Violation::new( + NAME, + "unpacked dimension counts downwards; write it as `[0:N-1]`", + dim.span, + )); + }); + out + } +} + +/// True when `[a:b]` demonstrably counts downwards. +/// +/// Two literals decide it outright. A right bound of literal `0` decides it +/// too whatever the left bound is — `[WIDTH-1:0]` is the shape this rule +/// mostly meets — unless the left bound is `0` as well, which is the +/// one-element `[0:0]` and counts in no direction at all. Anything else is +/// two symbolic bounds lucisv cannot compare, and it says nothing. +fn descending(a: &Expr, b: &Expr) -> bool { + match (literal(a), literal(b)) { + (Some(left), Some(right)) => left > right, + (None, Some(0)) => true, + _ => false, + } +} + +/// The value of a plain unsigned integer literal, or `None` for anything else. +fn literal(expr: &Expr) -> Option { + let ExprKind::Number(text) = &expr.kind else { return None }; + if text.contains(['\'', '.']) { + return None; + } + text.chars().filter(|c| *c != '_').collect::().parse().ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + UnpackedDimensionsRangeOrdering.check(&LintContext::new(src, None)) + } + + fn decl(text: &str) -> String { + format!("module m;\n {text}\nendmodule\n") + } + + #[test] + fn flags_a_descending_unpacked_range() { + let src = decl("logic q [7:0];"); + let found = violations(&src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], "[7:0]"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn flags_the_common_symbolic_to_zero_shape() { + assert_eq!(violations(&decl("logic q [DEPTH-1:0];")).len(), 1); + assert_eq!(violations(&decl("logic q [2:1];")).len(), 1); + } + + #[test] + fn an_increasing_range_is_what_the_rule_wants() { + for text in [ + "logic q [0:7];", + "logic q [0:DEPTH-1];", + "logic q [0:0];", + "logic q [8];", + "logic q [];", + "logic q [string];", + "logic q;", + ] { + let src = decl(text); + assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src)); + } + } + + #[test] + fn two_symbolic_bounds_are_left_alone() { + assert!(violations(&decl("logic q [LO:HI];")).is_empty()); + assert!(violations(&decl("logic q [A-1:B];")).is_empty()); + } + + #[test] + fn a_packed_dimension_is_the_other_rules_business() { + assert!(violations(&decl("logic [7:0] v;")).is_empty()); + // ... and both dimensions of one declaration are told apart. + assert_eq!(violations(&decl("logic [7:0] q [3:0];")).len(), 1); + } + + #[test] + fn every_declaration_shape_is_reached() { + let src = "module m #(parameter int P [1:0] = '{0, 0}) (\n\ + input logic a [1:0]\n\ + );\n\ + logic b [1:0];\n\ + typedef logic w_t [1:0];\n\ + function automatic void f(input logic x [1:0]);\n\ + endfunction\n\ + endmodule\n"; + assert_eq!(violations(src).len(), 5, "{:?}", violations(src)); + } +} diff --git a/crates/vlog_linter/src/rules/uvm_macro_semicolon.rs b/crates/vlog_linter/src/rules/uvm_macro_semicolon.rs new file mode 100644 index 0000000..504bdae --- /dev/null +++ b/crates/vlog_linter/src/rules/uvm_macro_semicolon.rs @@ -0,0 +1,118 @@ +//! `uvm-macro-semicolon` — no `;` after a `` `uvm_* `` macro invocation. + +use crate::context::LintContext; +use crate::preproc::macro_name; +use crate::registry::Rule; +use crate::severity::Severity; +use crate::violation::Violation; +use vlog_parser::token::TokenKind; + +/// See [`Rule::doc`]. +pub struct UvmMacroSemicolon; + +const NAME: &str = "uvm-macro-semicolon"; + +/// The prefix that marks a macro as UVM's. +const UVM: &str = "uvm_"; + +impl Rule for UvmMacroSemicolon { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "do not write a `;` after a `` `uvm_* `` macro invocation" + } + + fn severity(&self) -> Severity { + Severity::Warning + } + + fn default_on(&self) -> bool { + false + } + + fn doc(&self) -> &'static str { + "The UVM reporting macros expand to a `begin … end` block, so the `;` \ + so many people write after one is a *null statement* that follows it. \ + Usually harmless; not always — `if (x) `uvm_info(…); else …` puts the \ + null statement where the `if`'s body should be and the `else` then \ + belongs to nothing, which is a compile error or, worse, a silently \ + different branch structure. Verible's `uvm-macro-semicolon` (\"Checks \ + that no `uvm_*` macro calls end with ';'.\", **disabled** by default) \ + is the same rule and lucisv ships it off for the same reason: the \ + semicolon is written everywhere in existing UVM code and is almost \ + always inert, so turning it on is a project's decision.\n\n\ + A macro whose name begins `uvm_` is judged, whatever follows the \ + invocation's arguments; the finding points at the `;`. **No \ + automatic fix**: deleting the `;` is exactly the edit that is unsafe \ + in the one shape the rule exists for — after `if (x) `uvm_info(…);` \ + with no `else`, removing it is fine, and with one it changes which \ + statement the `else` binds to." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let tokens = ctx.tokens(); + let mut out = Vec::new(); + for (i, token) in tokens.iter().enumerate() { + let Some(name) = macro_name(token) else { continue }; + if !name.starts_with(UVM) { + continue; + } + let Some(next) = tokens.get(i + 1) else { continue }; + if next.kind != TokenKind::Symbol || next.text != ";" { + continue; + } + out.push(Violation::new( + NAME, + format!("`` `{name} `` already ends its statement; the `;` is a null statement"), + next.span, + )); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + UvmMacroSemicolon.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_the_semicolon_not_the_macro() { + let src = "module m;\n initial `uvm_info(\"A\", \"B\", UVM_LOW);\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(&src[found[0].span.as_range()], ";"); + assert!(found[0].fix.is_none()); + } + + #[test] + fn the_bare_invocation_is_what_the_rule_wants() { + let src = "module m;\n initial begin\n `uvm_info(\"A\", \"B\", UVM_LOW)\n end\n\ + endmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_non_uvm_macro_is_not_judged() { + let src = "module m;\n initial `my_macro(1);\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn every_uvm_macro_of_a_file_is_reported() { + let src = "module m;\n initial begin\n `uvm_info(\"A\", \"B\", UVM_LOW);\n \ + `uvm_error(\"A\", \"B\");\n `uvm_fatal(\"A\", \"B\")\n end\nendmodule\n"; + assert_eq!(violations(src).len(), 2, "{:?}", violations(src)); + } + + #[test] + fn a_semicolon_on_the_next_line_still_follows_the_macro() { + let src = "module m;\n initial `uvm_info(\"A\", \"B\", UVM_LOW)\n ;\nendmodule\n"; + assert_eq!(violations(src).len(), 1); + } +} diff --git a/crates/vlog_linter/src/rules/v2001_generate_begin.rs b/crates/vlog_linter/src/rules/v2001_generate_begin.rs new file mode 100644 index 0000000..eda28bf --- /dev/null +++ b/crates/vlog_linter/src/rules/v2001_generate_begin.rs @@ -0,0 +1,102 @@ +//! `v2001-generate-begin` — no bare `begin` inside a generate region. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::rules::module_begin_block::begin_block; +use crate::severity::Severity; +use crate::violation::Violation; +use crate::visit::walk_items; +use vlog_parser::ast::ItemKind; + +/// See [`Rule::doc`]. +pub struct V2001GenerateBegin; + +const NAME: &str = "v2001-generate-begin"; + +impl Rule for V2001GenerateBegin { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "do not write a bare `begin` block inside a generate region" + } + + fn severity(&self) -> Severity { + Severity::Style + } + + fn doc(&self) -> &'static str { + "A `begin … end` written directly inside `generate … endgenerate`, \ + with no `if`, `for` or `case` around it, was a Verilog-2001 spelling \ + for \"one more scope\". It opens an unnamed generate block, so every \ + declaration inside it acquires an invented path segment (`genblk1.x`) \ + that renumbers the moment a block is added above it — and it buys \ + nothing, because the region is already a scope. Verible's \ + `v2001-generate-begin` (\"Checks that there are no generate-begin \ + blocks inside a generate region.\", enabled by default) is the same \ + rule and the same default.\n\n\ + Like `module-begin-block`, this reads the error leaf lucisv's parser \ + leaves where it refused the construct: an item inside a \ + `generate … endgenerate` whose first token is `begin`. No automatic \ + fix — deleting the two keywords re-indents the whole block, and \ + giving it a label instead is a different repair." + } + + fn check(&self, ctx: &LintContext) -> Vec { + let mut out = Vec::new(); + walk_items(ctx.file(), &mut |item| { + let ItemKind::GenerateRegion { items, .. } = &item.kind else { return }; + for inner in items { + if let Some(span) = begin_block(inner) { + out.push(Violation::new( + NAME, + "bare `begin` block inside a generate region; the region is \ + already a scope", + span, + )); + } + } + }); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn violations(src: &str) -> Vec { + V2001GenerateBegin.check(&LintContext::new(src, None)) + } + + #[test] + fn flags_a_bare_begin_and_points_at_the_keyword() { + let src = "module m;\n generate\n begin : b\n wire a;\n end\n \ + endgenerate\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_generate_construct_inside_the_region_is_what_belongs_there() { + let src = "module m;\n generate\n\ + \x20 if (A) begin : g\n wire a;\n end\n\ + \x20 for (genvar i = 0; i < 2; i++) begin : l\n wire b;\n end\n\ + \x20 endgenerate\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_module_scope_block_belongs_to_the_other_rule() { + let src = "module m;\n begin\n wire a;\n end\nendmodule\n"; + assert!(violations(src).is_empty(), "{:?}", violations(src)); + } + + #[test] + fn a_file_with_no_generate_region_is_silent() { + assert!(violations("module m;\n wire a;\nendmodule\n").is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/void_cast.rs b/crates/vlog_linter/src/rules/void_cast.rs index f728049..62a0e52 100644 --- a/crates/vlog_linter/src/rules/void_cast.rs +++ b/crates/vlog_linter/src/rules/void_cast.rs @@ -1,6 +1,7 @@ //! `void-cast` — `void'(…)` around something that is not a call. use crate::context::LintContext; +use crate::options::{OptionDefault, OptionKind, OptionSpec}; use crate::registry::Rule; use crate::severity::Severity; use crate::violation::Violation; @@ -12,6 +13,15 @@ pub struct VoidCast; const NAME: &str = "void-cast"; +/// Verible's own forbidden-call list, which it hard-codes: `uvm_hdl_read` and +/// `randomize` (the bare call and the `obj.randomize()` method alike). +const OPTIONS: &[OptionSpec] = &[OptionSpec { + name: "forbidden_calls", + kind: OptionKind::List, + default: OptionDefault::List(&["uvm_hdl_read", "randomize"]), + doc: "calls whose result must be checked, so a `void'` cast of one is a bug", +}]; + impl Rule for VoidCast { fn name(&self) -> &'static str { NAME @@ -25,6 +35,10 @@ impl Rule for VoidCast { Severity::Warning } + fn options(&self) -> &'static [OptionSpec] { + OPTIONS + } + fn doc(&self) -> &'static str { "`void'(expr)` exists for exactly one purpose: calling a function for \ its side effect and saying out loud that the return value is being \ @@ -35,12 +49,19 @@ impl Rule for VoidCast { edit. Verible ships a `void-cast` rule (\"Checks that void casts do \ not contain certain function/method calls.\", enabled by default) \ with a different subject: **it forbids a named list of calls** whose \ - result must be checked (`randomize`, `uvm_hdl_read`). lucisv's is the \ - complementary check TODO §33 asked for — the operand must be a call \ - at all — and takes no list, so the two do not overlap and neither \ - replaces the other; the named-call form belongs with the per-rule \ - options of wave 2. No automatic fix: whether the repair is to delete \ - the cast or to add the missing call is the author's to decide.\n\n\ + result must be checked (`randomize`, `uvm_hdl_read`). lucisv checks \ + both halves in the one rule. The first is the check TODO §33 asked \ + for — the operand must be a call at all — and the second is \ + Verible's, spelled as the `forbidden_calls` option so a project can \ + name its own. A discarded `randomize()` is the classic version: it \ + returns 0 when the constraints could not be solved, and \ + `void'(randomize())` throws that away, so the test runs on with \ + whatever the object happened to hold. The two halves cannot both \ + fire on one statement — the first wants a call and the second wants \ + a particular one — so a `void'(randomize())` is reported once. No \ + automatic fix for either: whether the repair is to delete the cast, \ + to add the missing call or to check the result is the author's to \ + decide.\n\n\ Only a `void'(...)` standing **as a statement** is judged, which is \ the one place the construct belongs: a `void` value gives an \ enclosing expression nothing to do with it, so a `void'` buried in an \ @@ -48,16 +69,31 @@ impl Rule for VoidCast { } fn check(&self, ctx: &LintContext) -> Vec { + let forbidden = ctx.option_list(NAME, "forbidden_calls"); let mut out = Vec::new(); walk_all_stmts(ctx.file(), &mut |stmt| { let StmtKind::ExprStmt(expr) = &stmt.kind else { return }; let ExprKind::Cast { ty, expr: inner, pattern, .. } = &expr.kind else { return }; - if *pattern || !is_void(ty) || is_call(inner) { + if *pattern || !is_void(ty) { + return; + } + if !is_call(inner) { + out.push(Violation::new( + NAME, + "`void'(...)` around something that is not a call; nothing is being discarded", + expr.span, + )); + return; + } + let Some(called) = called_name(inner) else { return }; + if !forbidden.iter().any(|name| name == called) { return; } out.push(Violation::new( NAME, - "`void'(...)` around something that is not a call; nothing is being discarded", + format!( + "`{called}` returns a result that must be checked; do not cast it to `void`" + ), expr.span, )); }); @@ -65,6 +101,23 @@ impl Rule for VoidCast { } } +/// The name the cast operand calls — the last segment of the callee, so +/// `obj.randomize()`, `pkg::uvm_hdl_read()` and a bare `randomize()` all +/// answer the same word. +fn called_name(expr: &Expr) -> Option<&str> { + match &expr.kind { + ExprKind::Call { callee, .. } => match &callee.kind { + ExprKind::Ident(name) => Some(name), + ExprKind::Member { name, .. } | ExprKind::Scope { name, .. } => Some(name), + _ => None, + }, + ExprKind::Paren { inner, .. } => called_name(inner), + ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => called_name(base), + ExprKind::Cast { expr: inner, .. } => called_name(inner), + _ => None, + } +} + /// True for the casting type `void`, however it is spelled in the tree. fn is_void(ty: &Expr) -> bool { matches!(&ty.kind, ExprKind::Ident(name) if name == "void") @@ -116,18 +169,57 @@ mod tests { fn a_call_is_what_a_void_cast_is_for() { for text in [ "void'(f());", - "void'(obj.randomize());", "void'(pkg::f(1, 2));", "void'(q.pop_front());", "void'((f()));", "void'($cast(a, b));", - "void'(randomize(x) with { x inside {[0:7]}; });", "void'(q.sum() with (item.w));", ] { assert!(violations(&stmt(text)).is_empty(), "{text}: {:?}", violations(&stmt(text))); } } + /// Verible's half of the rule: a call whose result must be checked. + #[test] + fn a_forbidden_call_is_reported_however_it_is_written() { + for text in [ + "void'(randomize());", + "void'(obj.randomize());", + "void'(randomize(x) with { x inside {[0:7]}; });", + "void'(uvm_hdl_read(path, value));", + "void'(pkg::uvm_hdl_read(path, value));", + ] { + let found = violations(&stmt(text)); + assert_eq!(found.len(), 1, "{text}: {found:?}"); + assert!(found[0].message.contains("must be checked"), "{}", found[0].message); + assert!(found[0].fix.is_none()); + } + } + + #[test] + fn the_two_halves_never_both_fire_on_one_statement() { + // The operand is a call, so the "not a call" half is silent; it is a + // forbidden call, so the other half speaks — once. + assert_eq!(violations(&stmt("void'(randomize());")).len(), 1); + assert_eq!(violations(&stmt("void'(x);")).len(), 1); + } + + #[test] + fn the_forbidden_list_is_configurable() { + use crate::options::RuleOptions; + let src = stmt("void'(my_check());"); + assert!(violations(&src).is_empty()); + let mut options = RuleOptions::new(); + options.set_raw(NAME, "forbidden_calls", "[\"my_check\"]").expect("accepted"); + let found = VoidCast.check(&LintContext::new(&src, None).with_options(&options)); + assert_eq!(found.len(), 1, "{found:?}"); + // ... and the default names are no longer forbidden once replaced. + let randomized = stmt("void'(randomize());"); + assert!(VoidCast + .check(&LintContext::new(&randomized, None).with_options(&options)) + .is_empty()); + } + #[test] fn a_cast_to_something_else_is_not_this_rules_business() { for text in ["a = int'(x);", "a = logic'(x);", "a = my_t'(x);", "a = 4'(x);"] { diff --git a/crates/vlog_linter/src/visit.rs b/crates/vlog_linter/src/visit.rs index fc2a341..5c1d930 100644 --- a/crates/vlog_linter/src/visit.rs +++ b/crates/vlog_linter/src/visit.rs @@ -70,6 +70,66 @@ fn gen_block(block: &GenBlock, f: &mut dyn FnMut(&Item)) { items(&block.items, f); } +/// The declaration an item was written inside — what a rule needs when the +/// same construct is right in one scope and wrong in another. +/// +/// A generate construct is not a scope here: `localparam` inside a +/// `generate` block is still written in the module that holds it, and both +/// rules that ask this question (`proper-parameter-declaration`, the two +/// `explicit-*-lifetime`) mean the enclosing *declaration*, not the block. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ItemScope { + /// Written at file scope, outside every declaration. + File, + /// Inside a `module`, `interface` or `program` body. + Module, + /// Inside a `package` body. + Package, + /// Inside a `class` body. + Class, +} + +/// Calls `f` on every item of the file, saying which declaration holds it. +pub(crate) fn walk_items_scoped(file: &SourceFile, f: &mut dyn FnMut(ItemScope, &Item)) { + scoped_items(&file.items, ItemScope::File, f); +} + +fn scoped_items(list: &[Item], scope: ItemScope, f: &mut dyn FnMut(ItemScope, &Item)) { + for item in list { + f(scope, item); + match &item.kind { + ItemKind::Module(m) => scoped_items(&m.items, ItemScope::Module, f), + ItemKind::Class(class) => scoped_items(&class.items, ItemScope::Class, f), + ItemKind::Package { items: inner, .. } => scoped_items(inner, ItemScope::Package, f), + // A generate construct keeps the scope it was written in. + ItemKind::GenerateRegion { items: inner, .. } => scoped_items(inner, scope, f), + ItemKind::GenIf(gen_if) => { + scoped_items(&gen_if.then.items, scope, f); + let mut els = gen_if.els.as_deref(); + while let Some(branch) = els { + match branch { + GenElse::If(_, nested) => { + scoped_items(&nested.then.items, scope, f); + els = nested.els.as_deref(); + } + GenElse::Block(block) => { + scoped_items(&block.items, scope, f); + els = None; + } + } + } + } + ItemKind::GenFor(gen_for) => scoped_items(&gen_for.body.items, scope, f), + ItemKind::GenCase(gen_case) => { + for case_item in &gen_case.items { + scoped_items(&case_item.body.items, scope, f); + } + } + _ => {} + } + } +} + /// Calls `f` on every statement of the file, nested statements included. pub(crate) fn walk_all_stmts(file: &SourceFile, f: &mut dyn FnMut(&Stmt)) { // A statement fragment is a whole file of statements with no item around @@ -314,6 +374,41 @@ mod tests { assert_eq!(names, vec!["A".to_string(), "T".to_string()]); } + /// The scope a rule asks about is the enclosing *declaration*, and a + /// generate construct passes the one it was written in through. + #[test] + fn every_item_is_told_which_declaration_holds_it() { + let src = "localparam int AtFile = 0;\n\ + package p;\n\ + localparam int InPackage = 0;\n\ + class c;\n localparam int InClass = 0;\n endclass\n\ + endpackage\n\ + module m;\n\ + localparam int InModule = 0;\n\ + if (A) begin : g\n localparam int InGenerate = 0;\n end\n\ + endmodule\n"; + let (file, diagnostics) = parse_source_tolerant(src); + assert!(diagnostics.is_empty(), "{diagnostics:?}"); + let mut seen: Vec<(String, ItemScope)> = Vec::new(); + walk_items_scoped(&file, &mut |scope, item| { + if let ItemKind::ParamDecl(decl) = &item.kind { + for declarator in &decl.declarators { + seen.push((declarator.name.clone(), scope)); + } + } + }); + assert_eq!( + seen, + vec![ + ("AtFile".to_string(), ItemScope::File), + ("InPackage".to_string(), ItemScope::Package), + ("InClass".to_string(), ItemScope::Class), + ("InModule".to_string(), ItemScope::Module), + ("InGenerate".to_string(), ItemScope::Module), + ] + ); + } + #[test] fn an_unparsable_region_is_visited_but_holds_nothing() { let (file, diagnostics) = parse_source_tolerant("module m;\n @@@;\nendmodule\n"); diff --git a/crates/vlog_linter/tests/cases/empty_item.lint b/crates/vlog_linter/tests/cases/empty_item.lint index e06bb0b..4926a5f 100644 --- a/crates/vlog_linter/tests/cases/empty_item.lint +++ b/crates/vlog_linter/tests/cases/empty_item.lint @@ -74,9 +74,9 @@ endmodule ==== # `endfunction;` / `endtask;` are recorded on the declaration, not as null items module m; - function int f(); + function automatic int f(); endfunction; - task t(); + task automatic t(); endtask; endmodule ==== diff --git a/crates/vlog_linter/tests/cases/expression_style.lint b/crates/vlog_linter/tests/cases/expression_style.lint new file mode 100644 index 0000000..6c45d2c --- /dev/null +++ b/crates/vlog_linter/tests/cases/expression_style.lint @@ -0,0 +1,26 @@ +#select suggest-parentheses +# a conditional in the true-clause of another, and the safe fix that parenthesizes it +module m; + assign x = a ? b ? c : d : e; +//^ 18 suggest-parentheses + assign y = a ? b : c ? d : e; +endmodule +---- +module m; + assign x = a ? (b ? c : d) : e; +//^ 18 suggest-parentheses + assign y = a ? b : c ? d : e; +endmodule +==== +#select unpacked-dimensions-range-ordering +# an array counts up; a vector's width is the other rule's business +module m; + logic [7:0] v; + logic q [0:3]; + logic r [3:0]; +//^ 11 unpacked-dimensions-range-ordering + logic s [DEPTH-1:0]; +//^ 11 unpacked-dimensions-range-ordering + logic t [4]; + logic [LO:HI] u [LO:HI]; +endmodule diff --git a/crates/vlog_linter/tests/cases/generate_style.lint b/crates/vlog_linter/tests/cases/generate_style.lint new file mode 100644 index 0000000..a1cf36b --- /dev/null +++ b/crates/vlog_linter/tests/cases/generate_style.lint @@ -0,0 +1,56 @@ +#select legacy-generate-region,legacy-genvar-declaration +# the Verilog-2001 spellings, both off by default and both selected here +module m; + genvar i; +//^ 10 legacy-genvar-declaration + generate +//^ 3 legacy-generate-region + for (i = 0; i < 2; i++) begin : g_lanes + wire a; + end + endgenerate +endmodule +==== +#select legacy-generate-region,legacy-genvar-declaration +# the SystemVerilog spelling has neither +module m; + for (genvar i = 0; i < 2; i++) begin : g_lanes + wire a; + end +endmodule +==== +#select module-begin-block +# a sequential block written where a module item belongs +module m; + begin +//^ 3 module-begin-block + wire a; + end +endmodule +==== +#select module-begin-block,v2001-generate-begin +# a bare begin inside a generate region belongs to the other rule +module m; + generate + begin : b +//^ 5 v2001-generate-begin + wire a; + end + endgenerate +endmodule +==== +#select module-begin-block,v2001-generate-begin +# every legal block shape is silent +module m; + initial begin + a = 1; + end + always_comb begin + b = a; + end + generate + if (A) begin : g_a + wire c; + end + endgenerate +endmodule diff --git a/crates/vlog_linter/tests/cases/lifetimes.lint b/crates/vlog_linter/tests/cases/lifetimes.lint new file mode 100644 index 0000000..d3316a8 --- /dev/null +++ b/crates/vlog_linter/tests/cases/lifetimes.lint @@ -0,0 +1,43 @@ +#select explicit-function-lifetime,explicit-task-lifetime +# a subroutine outside a class must say which lifetime it has +module m; + function int f(int x); +//^ 16 explicit-function-lifetime + return x; + endfunction + task t(); +//^ 8 explicit-task-lifetime + endtask +endmodule +==== +#select explicit-function-lifetime,explicit-task-lifetime +# either keyword satisfies both rules +module m; + function automatic int f(int x); + return x; + endfunction + task static t(); + endtask +endmodule +==== +#select explicit-function-lifetime,explicit-task-lifetime +# a class method is exempt, and a prototype declares no locals +package p; + class c; + function int f(); + return 0; + endfunction + task t(); + endtask + extern function int g(); + endclass +endpackage +==== +#select explicit-function-lifetime +# a package-scope function is judged like a module's +package p; + function int f(); +//^ 16 explicit-function-lifetime + return 0; + endfunction +endpackage diff --git a/crates/vlog_linter/tests/cases/parameter_placement.lint b/crates/vlog_linter/tests/cases/parameter_placement.lint new file mode 100644 index 0000000..e2e19d1 --- /dev/null +++ b/crates/vlog_linter/tests/cases/parameter_placement.lint @@ -0,0 +1,39 @@ +#select positive-meaning-parameter-name +# a parameter named for what it turns off +module m #( + parameter int DisableEcc = 0 +//^ 17 positive-meaning-parameter-name +) (); + localparam int disable_crc = 1; +//^ 18 positive-meaning-parameter-name + localparam int EnableEcc = 1; +endmodule +==== +#select proper-parameter-declaration +# `parameter` in a body, `localparam` in a formal list +module m #( + parameter int Width = 8, + localparam int Half = Width / 2 +) (); + parameter int Depth = 4; +//^ 17 proper-parameter-declaration + localparam int Mask = 3; +endmodule +==== +#select proper-parameter-declaration +# a package takes `localparam` by default and `parameter` only when told to +package p; + localparam int A = 1; + parameter int B = 2; +//^ 17 proper-parameter-declaration +endpackage +==== +#select proper-parameter-declaration +#options proper-parameter-declaration.package_allow_parameter = true +#options proper-parameter-declaration.package_allow_localparam = false +# the two options move the line in opposite directions +package p; + localparam int A = 1; +//^ 18 proper-parameter-declaration + parameter int B = 2; +endpackage diff --git a/crates/vlog_linter/tests/cases/preprocessor.lint b/crates/vlog_linter/tests/cases/preprocessor.lint new file mode 100644 index 0000000..6ea2772 --- /dev/null +++ b/crates/vlog_linter/tests/cases/preprocessor.lint @@ -0,0 +1,78 @@ +#select forbidden-macro,uvm-macro-semicolon +# the default forbidden macro, and the `;` the UVM macros do not want +module m; + initial begin + `uvm_warning("A", "B") +//^ 5 forbidden-macro + `uvm_info("A", "B", UVM_LOW); +//^ 33 uvm-macro-semicolon + `uvm_error("A", "B") + end +endmodule +==== +#select forbidden-macro +#options forbidden-macro.macros = ["my_macro"] +# the option replaces Verible's one-name list +module m; + initial begin + `uvm_warning("A", "B") + `my_macro(1) +//^ 5 forbidden-macro + end +endmodule +==== +#select macro-string-concatenation +# `` inside a plain string is not evaluated; inside `"..."` it is +`define GLUE(a, b) $display("a``b") +//^ 31 macro-string-concatenation +`define OK(a, b) $display(`"a``b`") +module m; +endmodule +==== +#select endif-comment +# a bare `endif is named by the safe fix +`ifdef SYNTHESIS +module m; +endmodule +`endif +//^ 1 endif-comment +---- +`ifdef SYNTHESIS +module m; +endmodule +`endif // SYNTHESIS +//^ 1 endif-comment +==== +#select endif-comment +# nesting pairs each `endif with its own condition, and a naming comment passes +`ifdef A +`ifdef B +module m; +endmodule +`endif // B +`endif +//^ 1 endif-comment +==== +#select forbid-line-continuations +# a `define may be broken across lines and a string may not. The positive +# case has no marker home here: the finding lands on the *first* line of a +# multi-line string, and a marker attaches to the line above it — which is +# inside the string. Pinned in the rule's unit tests instead, as `posix-eof` +# is; what this case pins is that a multi-line macro is never reported. +`define TWO_LINES \ + wire a; \ + wire b; +module m; +endmodule +==== +#select numeric-format-string-style +# the prefix must name the base the specifier prints +module m; + initial begin + $display("0x%0h and 'b%0b and %d", a, b, c); + $display("0x%0b", a); +//^ 15 numeric-format-string-style + $display("0d%0d", a); +//^ 15 numeric-format-string-style + end +endmodule diff --git a/crates/vlog_linter/tests/cases/statements.lint b/crates/vlog_linter/tests/cases/statements.lint index 3e500e5..33b3e18 100644 --- a/crates/vlog_linter/tests/cases/statements.lint +++ b/crates/vlog_linter/tests/cases/statements.lint @@ -26,7 +26,7 @@ module m; void'(x); //^ 5 void-cast void'(f()); - void'(obj.randomize() with { a inside {[0:3]}; }); + void'(obj.pop() with { a inside {[0:3]}; }); end endmodule ==== diff --git a/crates/vlog_linter/tests/cases/uvm_style.lint b/crates/vlog_linter/tests/cases/uvm_style.lint new file mode 100644 index 0000000..6ef2764 --- /dev/null +++ b/crates/vlog_linter/tests/cases/uvm_style.lint @@ -0,0 +1,83 @@ +#select create-object-name-match +# the create name is the handle's name +class c; + function automatic void build(); + driver_h = my_driver::type_id::create("drv", this); +//^ 43 create-object-name-match + monitor_h = my_monitor::type_id::create("monitor_h", this); + endfunction +endclass +==== +#select void-cast +# the two halves of the rule: a non-call operand, and a call whose result must be checked +class c; + function automatic void run(); + void'(x); +//^ 5 void-cast + void'(f()); + void'(obj.randomize()); +//^ 5 void-cast + endfunction +endclass +==== +#select void-cast +#options void-cast.forbidden_calls = ["my_check"] +# the forbidden-call list is the project's +class c; + function automatic void run(); + void'(obj.randomize()); + void'(my_check()); +//^ 5 void-cast + endfunction +endclass +==== +#select invalid-system-task-function +#options invalid-system-task-function.symbols = ["$stop"] +# `symbols` is Verible's `forbidden-symbol` list, folded into this one rule +module m; + initial begin + a = $random(); + $stop; +//^ 5 invalid-system-task-function + end +endmodule +==== +#select disable-statement +# a fork label is not something `disable` may name +module m; + initial begin : seq + fork : threads + join_none + disable seq; + disable fork; + disable threads; +//^ 5 disable-statement + end +endmodule +==== +#select dff-name-style +# the `_q`/`_d` convention, its reset waiver and its mismatch +module m; + always_ff @(posedge clk) begin + if (!rst_ni) count <= '0; + else count_q <= count_d; + other_q <= wrong_d; +//^ 16 dff-name-style + plain <= count_d; +//^ 5 dff-name-style + end + assign result_q = count_d; +//^ 10 dff-name-style +endmodule +==== +#select dff-name-style +#options dff-name-style.output = ["ptr"] +#options dff-name-style.input = ["nxt"] +# the suffix lists are the project's +module m; + always_ff @(posedge clk) begin + data_ptr <= data_nxt; + data_q <= data_d; +//^ 5 dff-name-style + end +endmodule diff --git a/crates/vlog_linter/tests/cases/waivers.lint b/crates/vlog_linter/tests/cases/waivers.lint index 11a172f..a5bf64d 100644 --- a/crates/vlog_linter/tests/cases/waivers.lint +++ b/crates/vlog_linter/tests/cases/waivers.lint @@ -29,7 +29,7 @@ endmodule ==== # a verible waiver for a rule lucisv does not have is ignored module m; - // verilog_lint: waive explicit-function-lifetime + // verilog_lint: waive forbid-implicit-declarations wire a; endmodule ==== diff --git a/docs/coverage_gaps.md b/docs/coverage_gaps.md index 55ef9e2..a750b57 100644 --- a/docs/coverage_gaps.md +++ b/docs/coverage_gaps.md @@ -162,3 +162,35 @@ mid-line list positions (port/parameter lists, `case` label lists) stay inert, because a column-0 verbatim slice has no place inside a `Group`. The three stale READMEs named under the order were reconciled in the 0.33.0 documentation pass. + +## Linter addendum (2026-09-04, TODO §35) + +Three waves of linter expansion (§33, §34, §35) took the registry from 17 +rules to **73**, and with §35 lucisv implements **every rule in Verible's +published list except one**: `forbid-implicit-declarations`, which needs the +elaboration-order model lucisv does not have. Each rule cites its Verible +name, description and default in its own `doc`; `lucisv check --rules-doc` is +the generated truth. + +Three coverage notes the wave produced, none of them a language gap: + +- **`begin` where an item belongs is a parser gap, not a rule gap.** The + parser refuses a module-scope `begin … end` and a bare `begin` inside a + `generate` region rather than recovering either as a block, so recovery + unwinds and the rest of that unit is lost — `module-begin-block` and + `v2001-generate-begin` read the error leaf instead of a tree. Both + constructs are illegal (the first) or legacy (the second), so the finding + itself is exact; what is lost is every *other* rule's view of that file. + Filed here as the linter's one remaining "the rule reads a gap between + tokens" case, for a future parser round to recover as a labelled generate + block. +- **An `.svh` fragment included into a class body is judged as file scope.** + `explicit-function-lifetime` / `explicit-task-lifetime` report methods in a + fragment that only becomes a class body after `` `include``. Verible, which + also lints one file at a time, reports the same; 39 of the two rules' 101 + opentitan findings are that shape. Not fixable without following includes, + which is the same boundary `docs/features/fragment-mode/README.md` records. +- **Verible's `forbidden-symbol` is not a rule.** It is the name of the + source file Verible implements `invalid-system-task-function` in. lucisv + ships one rule with the list as its `symbols` option rather than two rules + that would both fire on `$psprintf`. diff --git a/docs/features/linter-expansion-3/README.md b/docs/features/linter-expansion-3/README.md new file mode 100644 index 0000000..fa1472d --- /dev/null +++ b/docs/features/linter-expansion-3/README.md @@ -0,0 +1,575 @@ +# linter expansion, wave 3 — the remaining Verible rules + +## Goal + +TODO §35. The rules Verible publishes that lucisv did not have: nineteen new +files on the §33/§34 pattern (severity, Verible name/description/default +cited in the rule's own `doc`, options through `OptionSpec`, true positives +and near-misses in unit tests, a `.lint` case, corpus + opentitan counts with +ten findings classified), plus the two reconciliations §35 asked for — +Verible's *forbidden-symbol* list folded into `invalid-system-task-function` +as a `symbols` option rather than shipped as a second rule that would fire +twice on `$psprintf`, and Verible's forbidden-call half of `void-cast` added +to lucisv's existing rule as a `forbidden_calls` option. The registry goes +from 54 rules to **73**, which is every rule in Verible's published list +except `forbid-implicit-declarations`. Plus §34's open LOW: a checked-in +`tests/e2e.rs` case for `lucisv.lint.options` over the wire. + +## Assumptions + +- **Verible is the reference, read during the round.** Every rule's `doc` + quotes its Verible equivalent's one-line description and states its + enabled-by-default flag, both read from + and — where the + published page is too thin to implement from — from the rule's own source + and test files under + `verible/verilog/analysis/checkers/` on 2026-09-04. Each deviation is + listed in the work log and named in the rule's own `doc`. +- **`forbidden-symbol` is not a Verible rule.** It is the name of the *source + file* (`forbidden-symbol-rule.cc`) in which Verible implements + `invalid-system-task-function`; that file's descriptor registers the name + `"invalid-system-task-function"` and its map is the ten `$psprintf` / + `$random` / `$srandom` / `$dist_*` entries lucisv already shipped. Shipping + a second rule would have meant two findings on every `$psprintf`, which is + what §35 forbade; the list is the `symbols` option instead. Verified by + reading the file, not from memory. +- **A parser that refuses a construct still lets a rule report it.** lucisv's + parser rejects a module-scope `begin … end` and a bare `begin` inside a + `generate` region (both are illegal or legacy), leaving an `ItemKind::Error` + leaf whose first token is `begin`. `module-begin-block` and + `v2001-generate-begin` read that leaf. The finding is exact — no legal item + in either scope starts with that keyword — but error recovery unwinds out of + the enclosing unit, so a file with one of these reports little else. Filed + as a parser gap in `docs/coverage_gaps.md`; see Handshakes. +- **A `.svh` fragment is judged as the file it is, not as the class it is + included into.** The two lifetime rules report methods in a fragment that + only becomes a class body after `` `include``. Verible, which also lints one + file at a time, reports the same. 39 of the two rules' 101 opentitan + findings are that shape. +- **Where an option list replaces a Verible constant, the default is + Verible's constant.** `forbidden-macro.macros` = `["uvm_warning"]`, + `void-cast.forbidden_calls` = `["uvm_hdl_read", "randomize"]`, + `invalid-system-task-function.symbols` = the ten names — so a run that + configures nothing behaves exactly as Verible does. `dff-name-style`'s four + options are Verible's, with its comma-separated strings written as lists + (which is how every other lucisv list option is spelled) and its + `waive_lhs_regex` default `(?i)mem.*` rewritten `[mM][eE][mM].*`, because + `crates/vlog_linter/src/regex.rs` implements no inline flags and refuses + `(?…)` by name. + +## Handshakes + +- **Consumed** — `vlog_parser::ast` (unchanged: `FunctionDecl::scope`, + `RawText`, `Genvar`, `GenerateRegion`, `StmtKind::Disable`, + `ExprKind::Ternary`/`Scope`/`Call` are all read as they stand), + `vlog_parser::token` (a macro invocation is one `Ident` starting with a + backtick; a directive is one `Directive` to end of line — both facts are now + read in one place, `crate::preproc`), `vlog_linter::options` and + `LintContext::option_*` from §34, unchanged. +- **Promised (new inside `vlog_linter`, all `pub(crate)`)** — + `visit::ItemScope` + `visit::walk_items_scoped` (the enclosing *declaration* + of an item), `exprs::walk_exprs` (every expression of a file), + `preproc::{macro_name, directive_word, directive_operand}`. No public API of + the crate changed; `Rule` and `OptionSpec` are exactly §34's. +- **Promised (user-visible)** — nineteen new rule names, and two new option + keys on rules that already existed: `invalid-system-task-function.symbols` + and `void-cast.forbidden_calls`. Both default to the behaviour 0.38.0 + shipped, and `invalid-system-task-function`'s finding list is **byte-identical** + to 0.38.0's on both trees (measured below). +- **Files touched outside `vlog_linter`, each minimal and named by §35:** + - `editors/vscode/package.json` — regenerated by + `cargo run -p vlog_linter --example vscode_lint_settings`; nothing + hand-edited. The drift test in `lucisv_server` proves it. + - `crates/lucisv_server/tests/e2e.rs` — one new test, §35's own item. + - `README.md`, `docs/site/src/content/docs/reference/rules.md`, + `docs/coverage_gaps.md`, `TODO.md` — documentation, §35's own items. +- **Handshake request to the parser (not made as an edit):** recover a + module-scope `begin … end` and a bare `begin` inside a `generate` region as + an unnamed generate block instead of an error leaf, so the *rest* of the + unit survives. Both rules would then read a tree, and every other rule would + keep working on such a file. Recorded in `docs/coverage_gaps.md`'s linter + addendum; no `vlog_parser` file was touched by this lane. +- **Not changed, deliberately** — `vlog_formatter`, `verify.rs`, + `vlog_parser` (`git diff` over all three is empty); the formatter's corpus + output is byte-identical to 0.38.0. + +## Status / TODO + +- [x] 35.1 the nineteen rules, each with unit tests, a `.lint` case and + corpus + opentitan counts +- [x] 35.2 `void-cast`'s `forbidden_calls`; `forbidden-macro`'s `macros`; + `invalid-system-task-function` reconciled with Verible's + `forbidden-symbol` (one rule, one `symbols` option — the decision and + its evidence are in Assumptions) +- [x] 35.3 a checked-in `tests/e2e.rs` case for `lucisv.lint.options` +- [x] 35.4 docs: README "Linting" rows, the docs-site rules page, the + `coverage_gaps.md` linter addendum, `package.json` regenerated +- [x] Gates (guarded): fmt, clippy 0, `cargo test --workspace` 3 695/48, + corpus 814/820, `--stdout` byte-identity 0 differing, vsix smoke, + opentitan census + timing +- [ ] QA + +## The rules, measured + +Counts are `lucisv check --select --no-config` over the 860-file corpus +and over `~/repo/opentitan/hw` (10 k files, read-only), with the release +binary of this branch. "V" is Verible's default for the same rule; lucisv +matches it for all nineteen. Ten findings per rule were read where there are +ten; where there are fewer, all of them were. + +| Rule | Sev | Default (V→here) | Verible equivalent | Options (default) | Corpus | opentitan | Findings read | +|---|---|---|---|---|---|---|---| +| `module-begin-block` | style | on→on | same | — | 0 | 0 | **0 on either tree** — no real file writes a sequential block at module scope, which is what makes it illegal. Pinned by unit tests and a `.lint` case, and confirmed firing through the release binary on a crafted file | +| `legacy-generate-region` | style | off→off | same | — | 6 | 3 | 9 true (all there are): `picorv32.v` ×3, `picorv32/scripts/{quartus,vivado}/system.v`, `common_cells/src/deprecated/generic_LFSR_8bit.sv`, `aes/pre_dv/…/tlul_delayer.sv`, `ascon/pre_dv/…/ascon_sim.sv`, `pulp_riscv_dbg/sva/dm_top_sva.sv`. Every one is Verilog-2001-era or vendored code — which is exactly why the rule ships off | +| `legacy-genvar-declaration` | style | off→off | same | — | 0 | 1 | 1 true (all there is): `pulp_riscv_dbg/sva/dm_top_sva.sv:55` writes `genvar i;` above the `for` that uses it — the same file `legacy-generate-region` flags one line earlier | +| `v2001-generate-begin` | style | on→on | same | — | 0 | 0 | **0 on either tree.** Pinned by unit tests and a `.lint` case, and confirmed firing through the release binary on a crafted file | +| `explicit-function-lifetime` | style | on→on | same | — | 29 | 32 | 10 read, all true: `.svh` fragments included into *modules* (`prim_util_memload.svh`, `prim_util_get_scramble_params.svh` — there a function really is static by default) and `pre_dv` program bodies. **The out-of-body exemption is what made this number honest**: before it, 948 of 960 findings across this rule and its twin were `function cls::f(…)` definitions, which are class methods | +| `explicit-task-lifetime` | style | on→on | same | — | 47 | 69 | 10 read: 2 true (`prim_util_memload.svh`'s `simutil_memload`, a `pre_dv` program task), 8 **needs judgment** — `cip_base_vseq__*.svh`, fragments `` `include``d *inside* a class body, where lucisv (and Verible, which also lints per file) cannot see the class. All in `dv/`, outside opentitan's lint filesets | +| `positive-meaning-parameter-name` | style | on→on | same | — | 0 | 0 | **0 on either tree** — neither codebase names a parameter `disable*`. Pinned by unit tests (four spellings, four near-misses) and a `.lint` case; confirmed firing through the release binary | +| `suggest-parentheses` | style | on→on | same | — | 0 | 0 | **0 on either tree** — `a ? b ? c : d : e` is written by nobody; people parenthesize. Pinned by unit tests (including three-deep) and a `.lint` case with its safe fix; confirmed firing through the release binary | +| `unpacked-dimensions-range-ordering` | style | on→on | same | — | 11 | 7 | 10 read, all true: `logic […] FIFO_REGISTERS[DATA_DEPTH-1:0]`, `payload_t data_fifo [DutNumInp-1:0][DutNumOut-1:0][$]`, `uint length[NUM_PATTGEN_CHANNELS-1:0]` — real descending arrays. The mirror image of `packed-dimensions-range-ordering`, and the two never both fire on one dimension | +| `uvm-macro-semicolon` | warning | off→off | same | — | 22 | 214 | 10 read, all true: `` `uvm_fatal(…); `` in the ibex cosim monitors, `` `uvm_create_obj(…); `` throughout `hw/dv/sv`. All in `dv/`+`vendor/`. Off, as Verible ships it — the `;` is inert in almost every one of them | +| `create-object-name-match` | warning | on→on | same | — | 1 | 4 | 5 true (all there are): `irq_single_seq_h` created as `irq_raise_single_seq_h`, `m_csrng_agent_cfg` created as `m_csrng_genbits_agent_cfg`, `item` as `sba_req`, `xbar_vseq` as `xbar_stress_all_vseq`. Every one is a config-db path that will not match what the reader expects | +| `numeric-format-string-style` | style | off→off | same | — | 4 | 6 | 6 true (all there are): `"host_delay = 0x%0d "` ×4 in `push_pull_item.sv` (a decimal printed behind a hex prefix) and `"'d%3d"` in `spid_upload_tb.sv`. Off, as Verible ships it | +| `macro-string-concatenation` | warning | off→off | same | — | 2 | 10 | 10 true: `` `define _ACCESS_CHECKS `` in `mem_bkdr_util.sv` writes `` "addr 0x%0h not ``_DW``-bit aligned" `` — a plain string, so the two backticks reach the output — and the alert-handler `vseq`s do the same. Off, as Verible ships it | +| `disable-statement` | warning | off→off | same | — | 0 | 4 | 4 true (all there are): `disable sar_simple_thread` / `sar_burst_thread` in `hmac_base_vseq.sv` and two in `lc_ctrl_smoke_vseq.sv`, every one naming a `fork : label`, which is the exact construct the rule exists for. Off, as Verible ships it | +| `forbidden-macro` | warning | on→on | `forbidden-macro` | `macros` (`["uvm_warning"]`) | 1 | 1 | 1 true on each tree (all there are): `riscv_instr_cov.svh:434` in `google_riscv-dv`, vendored into both. Verible hard-codes the list; here it is an option | +| `endif-comment` | style | off→off | same | safe fix | 398 | 706 | 10 read, all true: `common_cells/include/common_cells/assertions.svh` (`// UVM`, `// XSIM`, `// SYNTHESIS`), `bus_params_pkg.sv` (`// BUS_AW`, `// BUS_DW`, …). Off, as Verible ships it; the fix names the condition the `` `ifdef `` opened | +| `forbid-line-continuations` | style | on→on | same | — | 0 | 0 | **0 on either tree** — no file in either breaks a string with `\`. Pinned by unit tests and confirmed firing through the release binary; the `.lint` case pins the negative direction (a multi-line `` `define `` is never reported), because a marker cannot be written inside a multi-line string | +| `dff-name-style` | style | off→off | same | `input` (`["next","n","d"]`), `output` (`["reg","r","ff","q"]`), `waive_ifs_with_conditions` (Verible's four), `waive_lhs_regex` (`"[mM][eE][mM].*"`) | 385 | 2 233 | 10 read, all true *as the rule reads it*: `init`/`stalls` in `common_cells/formal/*`, `gpio_p2d`, `spi_device_sck_o` in `hw/dv/dpi/*` — registers not named `_q`. Neither codebase follows the `_q`/`_d` convention, which is why the rule ships off; a project that does gets a real check | +| `proper-parameter-declaration` | style | off→off | same | `package_allow_parameter` (false), `package_allow_localparam` (true) | 716 | 13 992 | 10 read, all true: `parameter` in package bodies (`bus_params_pkg.sv`, `alert_esc_agent_pkg.sv`) and in module bodies (`cdc_2phase_clearable_tb.sv`). opentitan writes `parameter` in packages everywhere, which the Verible default `package_allow_parameter = false` reports; one option accepts it. Off, as Verible ships it | + +Two options on rules that already existed: + +| Rule | Option (default) | Corpus | opentitan | Findings read | +|---|---|---|---|---| +| `void-cast` | `forbidden_calls` (`["uvm_hdl_read", "randomize"]`) | 0 → **3** | 0 → **3** | 6 true (all there are): `void'(randomize())` in `id_queue_tb.sv` ×2, `stream_register_tb.sv`, `entropy_src_env_cfg.sv`, `entropy_src_tb.sv`, and `void'(uvm_hdl_read(…))` in `hmac_directed_vseq.sv`. Every one discards a result that says whether the operation worked | +| `invalid-system-task-function` | `symbols` (the ten names) | 8 → 8 | 23 → 23 | **byte-identical to 0.38.0** on both trees, stdout and stderr — the option's default reproduces the hard-coded list exactly | + +**Why a Verible-default rule fires inside opentitan at all.** opentitan lints +its `hw/ip/*/rtl` filesets with +`hw/lint/tools/veriblelint/lowrisc-styleguide.rules.verible_lint`, which was +read for this round: it sets `line-length=length:100`, +`explicit-parameter-storage-type=exempt_type:string`, +`parameter-name-style=localparam_style:CamelCase|ALL_CAPS` and disables +`typedef-structs-unions` — and says **nothing** about any of §35's rules. So +Verible on opentitan's own filesets would report the same findings the five +default-on rules with non-zero counts produce here. It does not, in practice, +because those filesets are `rtl/` only: of the 116 new default-on findings on +`hw/`, **8 are under an `rtl/` path** — five of them in `hw/ip/prim/rtl/` +`.svh` fragments (`prim_util_memload.svh`, `prim_util_get_scramble_params.svh`, +which are simulation-only helpers `` `include``d into a module and are +genuinely static there), three in `pre_dv`/`pre_sca` testbench `rtl/` +directories — and the other 108 are in `dv/`, `pre_dv/`, `sva/`, `dpi/` and +`vendor/`, which opentitan's dvsim lint does not cover. That is the whole +explanation — no reading of a rule differs from Verible's. + +**The census.** The default set now reports **1 169** findings on opentitan +`hw/` against 0.38.0's 1 053, and **8 524** on the corpus against 8 432. Both +deltas are exactly the new default-on work: + +``` +opentitan 32 + 69 + 7 + 4 + 1 + 3 = 116 (= 1169 − 1053) +corpus 29 + 47 + 11 + 1 + 1 + 3 = 92 (= 8524 − 8432) +``` + +— `explicit-task-lifetime`, `explicit-function-lifetime`, +`unpacked-dimensions-range-ordering`, `create-object-name-match`, +`forbidden-macro`, and `void-cast`'s new named-call half. The other four +default-on rules (`module-begin-block`, `v2001-generate-begin`, +`positive-meaning-parameter-name`, `suggest-parentheses` and +`forbid-line-continuations` — five of them) contribute nothing on either +tree. + +## Work log + +### 2026-09-04 — dev (Opus 5) + +**35.1, the nineteen rules.** Written in §35's order: the two `forbidden-*` +list rules first (which is where the `forbidden-symbol` reconciliation had to +be settled), then the Style rules, then the Warning rules. + +Three shared readers were added inside the crate rather than duplicated +across rules, each one sentence long: + +- `visit::walk_items_scoped` + `visit::ItemScope` — the enclosing + *declaration* of an item (file, module, package, class), with generate + constructs passing the scope through. Read by both lifetime rules and by + `proper-parameter-declaration`. +- `exprs.rs` — `walk_exprs`, every expression of a file: the roots (a + continuous or procedural assignment, a declaration initialiser, a + condition, a call argument, an instantiation's connections, a generate + header, an expression statement, a parameter port's default) and a descent + through every composite `ExprKind`. Only `suggest-parentheses` needs it + today, and it needs *all* of it — a rule that judged expression shape from + a partial walk would be silently blind. +- `preproc.rs` — `macro_name`, `directive_word`, `directive_operand`. Four + rules read the lexer's two preprocessor token shapes; reading them in one + place is what stops the four disagreeing about where a name ends. + +**Decisions and deviations, for the lead:** + +- **`forbidden-symbol` ships as an option, not a rule.** Verible's + `forbidden-symbol-rule.cc` registers the descriptor name + `"invalid-system-task-function"` — the two names §35 listed separately are + one rule under its file name. lucisv keeps the one rule and gives it + `symbols`; the rule's `doc` says so in as many words, so nobody + re-derives it. Finding list byte-identical to 0.38.0's. +- **`void-cast` now checks both halves in one rule.** lucisv's original + question (the operand must be a call) and Verible's (a named list of calls + must not be discarded). They cannot both fire on one statement — the first + wants any call, the second a particular one — so a `void'(randomize())` is + reported once. Option name `forbidden_calls` is lucisv's; Verible has none. +- **`module-begin-block` and `v2001-generate-begin` read an error leaf.** The + parser refuses both constructs; the rules read the `ItemKind::Error` whose + first token is `begin`, one at module scope and one inside a + `GenerateRegion`. `begin_block()` is written once (in + `module_begin_block.rs`) and shared, so the two cannot disagree about what + a stray `begin` looks like. The parser gap is a Handshake request, not an + edit. +- **Both lifetime rules exempt an out-of-body definition**, which is wider + than Verible. `function cls::f(…); … endfunction` is lexically outside the + class and Verible reports it; it *is* a class method, and its lifetime is + already automatic. The first opentitan census, before the exemption, was + 948 findings of exactly that shape out of 960 — a census-driven fix of the + kind §34's `generate-label` produced. `FunctionDecl::scope` / + `TaskDecl::scope` is non-empty for exactly those declarations. +- **`disable-statement` also accepts a task or function name.** `disable + task_name` is legal (IEEE 1800 §9.6.2) and Verible reports it; reporting it + would be a false positive on a rule whose point is "write `disable fork`". + Named in the rule's `doc`. +- **`suggest-parentheses` implements Verible's shape and no more.** §35 + mentioned "or a mixed-precedence expression"; Verible's rule is only the + nested-true-clause one (`suggest-parentheses-rule.cc`: the true-case child, + unwrapped, is itself a condition expression), and a rule that guessed at + operator combinations would report far more than it explained. Its safe fix + inserts two characters and changes no token. +- **`dff-name-style`'s `waive_lhs_regex` default is `[mM][eE][mM].*`**, not + Verible's `(?i)mem.*`: lucisv's pattern engine refuses `(?…)` by name + (§34's rework), and the rewritten pattern accepts the same names. Its three + list options are Verible's comma-separated strings written as lists. + Conditions are compared with whitespace squeezed out, so `!rst_ni` and + `! rst_ni` are one waiver. +- **`endif-comment`'s fix is offered only where there is no comment at all.** + A comment that names something else is reported without one: rewriting + somebody's words is not a repair. +- **`numeric-format-string-style` was implemented from Verible's own test + file**, whose accepted and rejected literal lists are reproduced verbatim + as two unit tests (13 accepted, 10 rejected). A specifier with no prefix is + always accepted; only a mismatched prefix, and any prefix before a decimal + specifier, are reported. +- **`forbid-line-continuations` has no positive `.lint` case.** The finding + lands on the *first* line of a multi-line string and the harness attaches a + marker to the line above it, which is inside the string. Pinned by unit + tests instead — the same situation `posix-eof` is in, and the case file says + so while pinning the negative direction (a multi-line `` `define `` is never + reported). +- **Three existing test fixtures named `explicit-function-lifetime` as a rule + lucisv does not have** (`lib.rs`'s waiver test, `waivers.lint`) or wrote a + lifetime-less subroutine (`empty_item.lint`), and one `.lint` case wrote + `void'(obj.randomize() with …)` as a clean void cast. All four now name + `forbid-implicit-declarations` — Verible's one remaining unimplemented rule + — or say `automatic`, or call something else. Noted because they are §34 + files. + +**35.2** — the two option additions, above. + +**35.3** — `tests/e2e.rs` gained +`the_lint_options_setting_changes_what_is_published_and_a_bad_entry_is_logged`: +a `lucisv.toml` with `[lint.line-length] length = 40` flags a 47-column line; +`lucisv.lint.options` with `length: 200` clears it mid-session (the editor +beats the toml, key by key); a typo'd `lenght` is refused, logged as exactly +one `window/logMessage` naming the setting and ending "ignored", and dropped — +so the `lucisv.toml` value stands again and the finding comes back. That is +§34's open LOW closed with the behaviour its QA verified by hand twice. + +**35.4** — `README.md` (19 rows, verified against `--rules-doc`'s 73 names by +diff), the docs-site rules page (badge 54 → 73, 19 table rows and 19 sections, +headers diffed against `--rules-doc` — identical sets), +`docs/coverage_gaps.md`'s linter addendum (the Verible-coverage claim, the +parser gap, the fragment boundary, the `forbidden-symbol` note), and +`editors/vscode/package.json` regenerated by the generator. No setting was +added, so `editors/vscode/README.md` is unchanged — its "54 rules in all" +line is inside the *0.38.0 highlights* section and is historical. + +## Measurements + +All runs under `tools/guard.sh`; **no guard kill at any point**. + +- **`cargo test --workspace`**: **3 695 passed, 0 failed, 42 ignored** over + **48** test binaries (baseline 3 564 / 48 / 42) — +131 tests, no binary + added or removed. The `.lint` table went from 246 to **275** cases. +- **fmt**: `cargo fmt -p vlog_linter`, `cargo fmt -p lucisv_server`. + **clippy**: `cargo clippy --all-targets --workspace`, **0 warnings**, and no + new `#[allow]` anywhere in the diff. +- **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.38.0`: + **0 differ**. `git diff` over `vlog_formatter`, `vlog_parser` and + `verify.rs` is empty. +- **`invalid-system-task-function` identity**: `check --select + invalid-system-task-function --no-config`, this build vs 0.38.0 — corpus + **8 findings**, opentitan **23 findings**, stdout and stderr byte-identical + on both trees. +- **opentitan `check` census**: default set **1 169** findings against + 0.38.0's **1 053**; corpus **8 524** against **8 432**. The arithmetic is + above and balances exactly. +- **opentitan `check` timing** (three interleaved runs each, timed inside the + guard): 0.38.0 **0.86 / 0.84 / 0.84 s**, this build **0.86 / 0.86 / 0.85 s** + — no measurable difference, though the new build runs ten 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 + `lucisv check` and read-only. + +## QA log + +### 2026-09-04 — QA (Sonnet 5) + +Verified in the `lint-3` worktree only, everything guarded, opentitan +read-only. Scratch under `.../scratchpad/qa-35/`. + +**1. Gates, all reproduced independently.** `cargo fmt --all -- --check` +clean. `cargo clippy --all-targets --workspace`: 0 warnings; `git diff +b1b3cad` shows no new `#[allow]` anywhere (grepped the whole diff, not just +the new files). `cargo test --workspace --no-fail-fast` (full log, not +tail-truncated, so every binary's `test result:` line was summed): **3 695 +passed / 0 failed / 42 ignored / 48 binaries** — exact match, no guard kill. +`git diff --stat b1b3cad -- crates/vlog_formatter crates/vlog_parser`: empty. +Corpus gate (own build of `scripts/score.sh target/release/lucisv`, main +tree's `corpus/`, read-only): `{"passing":814,"total":820,"pct":99.3}`, same +five failure categories (2 invalid-or-fragment, 1 directive-split, 1 +macro-items, 1 not-verilog, 1 other). `--stdout` byte-identity over all 860 +corpus files, this build vs `~/.cache/lucisv-baselines/lucisv-0.38.0`: **0 +differ**. vsix smoke: `node editors/vscode/smoke.js target/release/lucisv-server` +— OK, 20 messages. Changed-file set: `git diff --stat b1b3cad` (15 tracked +files) plus the 20 untracked additions (19 rule files + the feature README) +match §35's ownership list exactly — nothing touched outside `vlog_linter`, +the two disclosed doc/toggle files, and the checked-in e2e test; the new +`the_lint_options_setting_changes_what_is_published_and_a_bad_entry_is_logged` +test in `crates/lucisv_server/tests/e2e.rs` was confirmed present in the run +(`ok`, line 1797 of the full log). + +**2. `forbidden-symbol` reconciliation.** Read Verible's actual +`forbidden-symbol-rule.cc` (`verible/verilog/analysis/checkers/`, GitHub +API-fetched, not from memory): its C++ class is `ForbiddenSystemTaskFunctionRule` +but the descriptor name it registers is `"invalid-system-task-function"` +under topic `"forbidden-system-functions"`, and its hard-coded map is exactly +the ten names lucisv ships (`$psprintf`→`$sformatf`, `$random`→`$urandom`, +`$srandom`→`process::self().srandom()`, the six `$dist_*`→`$urandom`) — +confirms the dev's claim word for word. CLI: `$psprintf` fires exactly once +with defaults; `[lint.invalid-system-task-function] symbols = ["$foo"]` +makes `$foo` fire and `$psprintf` stop firing (verified both directions). +Finding-list byte-identity, this build vs 0.38.0, `--select +invalid-system-task-function --no-config`: corpus **8** findings, opentitan +**23** findings, `diff` empty on both trees both ways. `git -C +~/repo/opentitan status --porcelain` before/after: only the three +pre-existing files — read-only held. + +**3. The nineteen rules, adversarially.** Read all 19 rule source files in +full (not just the diff) plus `exprs.rs` and `preproc.rs`; every rule's own +unit-test block already exercises true positive / near-miss / edge shapes +(macro text, fragments, class bodies, generate scopes) matching what its +`doc` claims — no gap between doc and code found in any of the 19. Targeted, +independent CLI/CLI-toml/LSP probes on top of reading: + +- `module-begin-block` / `v2001-generate-begin`: crafted a module-scope + `begin…end` and a bare `begin` in a `generate` region. Each fires exactly + once, span is exactly the 5-character `begin` keyword (confirmed via + `--output-format json` `range`), and no other rule misfires on the file + (only the incidental `module-filename` mismatch from my own test + filename). Confirmed via Verible's actual source + (`module-begin-block-rule.cc`, `v2001-generate-begin-rule.cc`) that both + are real Verible rule names with exactly the cited descriptions, both + enabled by default, and that `v2001-generate-begin`'s matcher + (`NodekGenerateRegion(HasGenerateBlock())`) does not distinguish a labelled + from an unlabelled block — so the rule's own test using `begin : b` is + correct, not a bug. +- **Lifetime exemption**: `class c; extern function int f(); endclass + function c::f(); return 0; endfunction` (out-of-body definition) is + **silent**; a bare `function int f(); return 0; endfunction` at module + scope **fires**. Both confirmed live via the CLI, matching the doc and the + 948/960 census claim. +- `disable-statement`: a fork label, a task name and an undeclared name in + one file — CLI confirms `disable threads` (fork label) and `disable + somewhere_else` (undeclared) fire, `disable t` (task) is silent. Read + Verible's real `disable-statement-rule.cc`: it matches only `kSeqBlock` + labels and does **not** special-case a task/function name, so lucisv's + "wider than Verible" claim (avoiding a false positive on the + IEEE-1800-legal `disable task_name`) is a genuine, correctly-cited + deviation, not an invented one. +- `suggest-parentheses`: confirmed the rule's scope is deliberately narrow by + reading Verible's actual `suggest-parentheses-rule.cc` — it contains a + literal `// TODO: evaluate other types of expressions` and only matches a + `kConditionExpression` nested in another's true-clause, nothing about + mixed-precedence operators. So `a + b << c`, `a & b | c`, `!a == b` and a + five-operator chain (`a | b & c ^ d << e >> f`) correctly produce **no** + finding (exit 0, confirmed) — this is lucisv matching Verible's real + scope, not an incomplete implementation. On the true-positive shape `a ? b + ? c : d : e`: `--fix` on a hand-written file parses (`lucisv --check` + exit 0 after the fix), is idempotent through the formatter (a `lucisv + format` pass afterward makes zero changes), and re-linting the fixed file + is clean. Truth-tabled `a ? (b ? c : d) : e` against the unparenthesized + original for all 32 combinations of 5 boolean inputs in Python: **0 + mismatches** — the fix is semantically inert by construction (parens make + explicit what right-associativity already meant). +- `endif-comment`: `--fix` on a hand-written file with a bare and a + `` `ifndef``/`` `else`` pair both parses and is idempotent (a `lucisv + format` pass afterward is a no-op on a second run), and the fixed + diagnostics clear. **One LOW finding**: the fix's insertion + (`crates/vlog_linter/src/rules/endif_comment.rs:102`, + `format!(" // {name}")`) writes **two** spaces before the comment, but + lucisv's formatter's canonical trailing-comment spacing is **one** space + (confirmed against `crates/vlog_formatter/src/fence.rs`'s own test + fixtures, e.g. `"wire a; // note"`) — so `lucisv --check` on a + freshly-`--fix`ed file reports "would reformat" immediately, and only + settles after one `lucisv format` pass. Not a correctness bug: the file + still parses, the eventual output is semantically identical and + idempotent, and `Applicability::Safe` is documented as "preserves meaning + and intent" only, not "already formatter-clean" — but it is a real, + fixable inconsistency (one character) worth a follow-up so a `--fix` run + does not leave a file that immediately fails `--check`. +- Option-bearing rules, **CLI toml** (all five): `invalid-system-task- + function.symbols` (above); `dff-name-style`'s four options set together + (`input`, `output`, `waive_ifs_with_conditions`, `waive_lhs_regex`) turn a + file with three otherwise-reportable shapes fully clean; `forbidden- + macro.macros = ["my_macro"]` fires only `my_macro`, not the default + `uvm_warning`; `void-cast.forbidden_calls = ["my_risky_call"]` fires only + that name, not `randomize`; `proper-parameter-declaration`'s two booleans + confirmed via its own unit tests (`package_allow_parameter`, + `package_allow_localparam`, both directions) plus a live check below. + **LSP editor object**, a standalone Python script speaking framed + JSON-RPC at the real `lucisv-server` binary (same technique + linter-expansion-2's QA used, since no other checked-in e2e case touches + these three): `forbidden-macro.macros` replaced live — the pre-push + publish flags `` `uvm_warning ``, the post-push publish (`macros: + ["my_macro"]`) flags `` `my_macro `` instead, on the same file; `void- + cast.forbidden_calls` emptied live — pre-push 1 finding, post-push 0; + `proper-parameter-declaration.package_allow_parameter` — pre-push 0 (rule + is off by default, confirmed correct, not a bug), post-select-push 1, + post-option-push 0. All three behaved exactly as configured, no crash, no + stray diagnostic. +- `void-cast`'s two halves never double-fire: confirmed via its own unit + test (`the_two_halves_never_both_fire_on_one_statement`) and via the CLI + toml probe above (`my_risky_call` reported once). + +**4. Opentitan census, re-derived independently.** Own build's default-set +`check --no-config` over `hw/`: **1 169** findings; 0.38.0's: **1 053** +(re-run myself, not taken from the README). Corpus: **8 524** vs 0.38.0's +**8 432** (also re-run). Delta arithmetic reproduced exactly: opentitan +32+69+7+4+1+3=116=1169−1053, corpus 29+47+11+1+1+3=92=8524−8432, checked +per-rule with a `--select ` sweep over all nineteen rules on both +trees — **every one of the 19 rows in the README's table matches my own +count exactly** (module-begin-block 0/0, legacy-generate-region 6/3, +legacy-genvar-declaration 0/1, v2001-generate-begin 0/0, +explicit-function-lifetime 29/32, explicit-task-lifetime 47/69, +positive-meaning-parameter-name 0/0, suggest-parentheses 0/0, +unpacked-dimensions-range-ordering 11/7, uvm-macro-semicolon 22/214, +create-object-name-match 1/4, numeric-format-string-style 4/6, +macro-string-concatenation 2/10, disable-statement 0/4, forbidden-macro +1/1, endif-comment 398/706, forbid-line-continuations 0/0, dff-name-style +385/2233, proper-parameter-declaration 716/13992), plus `void-cast` 0→3 on +both trees. `git -C ~/repo/opentitan status --porcelain` checked before and +after every sweep: only the three pre-existing files, every run read-only. + +Five findings classified for each of the five named rules: +- `explicit-task-lifetime`: read 5 of opentitan's 69 — + `cip_base_vseq__sec_cm_fi.svh` tasks (`run_sec_cm_fi_vseq`, + `pre_run_sec_cm_fi_vseq`, `post_run_sec_cm_fi_vseq`, + `check_sec_cm_fi_resp`, `test_sec_cm_fi`), all `.svh` fragments + `` `include``d into a class body — matches the README's "needs judgment" + bucket exactly (lucisv, like Verible, cannot see the class from the + fragment's own scope). +- `suggest-parentheses`: 0 on opentitan — matches the README, nothing to + classify. +- `unpacked-dimensions-range-ordering`: read 5 of 7 — + `pattgen_agent_cfg.sv:15`, `kmac_reduced_tb.sv:338` and `:354`, + `ram_1p.v:24`, `pattgen_scoreboard.sv:22`, all genuine descending unpacked + ranges — true positives, matches the README's characterization. +- `create-object-name-match`: read all 4 (all there are) — + `edn_env_cfg.sv` (`m_csrng_genbits_agent_cfg`/`m_csrng_agent_cfg`), + `rv_dm_buffered_enable_vseq.sv` (`sba_req`/`item`), + `xbar_stress_all_with_rand_reset_vseq.sv` + (`xbar_stress_all_vseq`/`xbar_vseq`), `core_ibex_vseq.sv` + (`irq_single_seq_h`/`irq_raise_single_seq_h`) — exactly the four the + README names, all true positives. +- `forbid-line-continuations`: 0 on opentitan — matches the README, nothing + to classify. + +No misclassification found in any finding read. Timing, three interleaved +runs each (`/usr/bin/time -p` inside the guard, default-set `check +--no-config` over `hw/`): 0.38.0 **0.85 / 0.86 / 0.83 s**, this build +**0.87 / 0.91 / 0.84 s** — within noise of the README's own numbers, no +regression over 10%. + +**5. Docs.** `lucisv check --rules-doc`: **73** `## ` sections. README.md's +"Linting" table: 73 rule rows (excluded the three-row severity legend after +first miscounting it, same trap linter-expansion-2's QA hit) — diffed +against `--rules-doc`'s name set: **identical**. `docs/site/src/content/ +docs/reference/rules.md`: 73 `## ` headers, diffed against `--rules-doc`: +**identical**. `editors/vscode/package.json`: 73 +`lucisv.lint.rules.` toggles, diffed against `--rules-doc`: +**identical** — and the drift test is not vacuous: in a throwaway worktree +(`git worktree add --detach` from `b1b3cad`, the dev's diff applied with +`git apply`, untracked files copied over, removed after with `git worktree +remove --force`), 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 registry side only. `git worktree list` afterward: +back to the original two worktrees. `docs/coverage_gaps.md`'s "Linter +addendum (2026-09-04, TODO §35)" section reads true against the shipped +code: the 73/74-rule count, the parser-gap note for the two `begin`-reading +rules, the `.svh`-fragment boundary, and the `forbidden-symbol` note all +match what I verified above. TODO §35's checkboxes match this README's +Status/TODO (35.1–35.4 and Gates ticked, QA still open pending this entry). +The four renamed §34 fixtures (`crates/vlog_linter/src/lib.rs`'s two waiver +tests, `tests/cases/waivers.lint`, `tests/cases/empty_item.lint`, +`tests/cases/statements.lint`) now name `forbid-implicit-declarations` (the +one Verible rule lucisv still lacks) or write `automatic`/a different call, +and all ran green in the full workspace test log +(`a_verible_waiver_for_a_rule_lucisv_does_not_have_is_ignored ... ok`). + +**Verdict: PASS.** One LOW finding: `endif-comment`'s safe fix inserts two +spaces before its trailing comment where lucisv's formatter's canonical +style is one, so a freshly-`--fix`ed file needs one `lucisv format` pass to +be `--check`-clean (`crates/vlog_linter/src/rules/endif_comment.rs:102`). +Harmless — parses, idempotent, semantically identical, and +`Applicability::Safe` never promised formatter-clean output — but worth the +one-character fix in a follow-up. Everything else verified clean: all +gates reproduced independently and matching exactly; the `forbidden-symbol` +reconciliation confirmed against Verible's actual source, not the dev's +citation of it; all nineteen rules read in full and adversarially probed, +including two rules' scope-narrowing decisions (`suggest-parentheses`, +`disable-statement`) independently confirmed against Verible's own source +rather than taken on the dev's word; the lifetime exemption and the two +error-leaf rules' isolation confirmed live; every option-bearing rule +exercised through the CLI toml, and three of them through a live LSP +session with the editor's value observed to win; the opentitan and corpus +censuses re-derived independently and matching the README's table and +arithmetic exactly, five findings apiece classified for the five named +rules with no misclassification; the docs, the drift test's teeth, and the +renamed §34 fixtures all confirmed. + +## Review + +**2026-09-04 — lead.** Accepted. With this wave every rule in Verible's +published list is in lucisv except the one that needs a compiler, and +the round's best decision was reading Verible's source rather than its +table: `forbidden-symbol` is the file name of `invalid-system-task- +function`, so it is an option, not a second rule that would have fired +twice on `$psprintf`. The census-driven narrowing of the lifetime rules +(948 of 960 findings were out-of-body definitions) is the right kind of +divergence, written down; the two rules that fire on an error leaf are +honest about the parser's limit and file it (`docs/topo.md` §2.9-25). +QA read the nineteen files, verified two scope decisions against +Verible's own source, truth-tabled the parenthesizing fix, and drove +the options through both doors. The one LOW — the `endif-comment` fix +wrote two spaces where the formatter writes one — fixed at review with +its two expectations. Ships in 0.39.0. The linter now stands at 73 +rules with severities, toggles and options; what remains for it is +measurement in use, not more rules. diff --git a/docs/site/src/content/docs/reference/rules.md b/docs/site/src/content/docs/reference/rules.md index 8ae3ad1..a0fd5d8 100644 --- a/docs/site/src/content/docs/reference/rules.md +++ b/docs/site/src/content/docs/reference/rules.md @@ -3,7 +3,7 @@ title: Lint rules description: Complete reference for every lucisv lint rule, its severity, default, fix, and rationale. --- -54 rules indexed +73 rules indexed Every rule is in one of three **severity** classes. `error` is code that would very likely fail to compile, elaborate or synthesize; `warning` is code that compiles and very likely does not mean what it says; `style` is code that is correct and reads badly. The class is the word in the CLI diagnostic line (`FILE:LINE:COL: warning: …`), the `severity` field of `--output-format json`, and the colour of the editor's squiggle — and it is accepted wherever a rule name is, so `--ignore style` and `--select error` both work. @@ -79,6 +79,25 @@ A rule marked **on (project)** runs by default only where lucisv can see th | [`unused-waiver`](#unused-waiver) | style | on | — | Remove ineffective suppressions | | [`void-cast`](#void-cast) | warning | on | — | Cast to `void` only what a call returns | | [`wire-reg-mixup`](#wire-reg-mixup) | error | on | — | Prefer `logic` to `reg` in SystemVerilog | +| [`create-object-name-match`](#create-object-name-match) | warning | on | — | Name a `type_id::create` after its handle | +| [`dff-name-style`](#dff-name-style) | style | off | — | Name a flip-flop `_q` and its input `_d` | +| [`disable-statement`](#disable-statement) | warning | off | — | Write `disable fork`, not a fork label | +| [`endif-comment`](#endif-comment) | style | off | safe | Say what an `` `endif `` closes | +| [`explicit-function-lifetime`](#explicit-function-lifetime) | style | on | — | State a function's lifetime outside a class | +| [`explicit-task-lifetime`](#explicit-task-lifetime) | style | on | — | State a task's lifetime outside a class | +| [`forbid-line-continuations`](#forbid-line-continuations) | style | on | — | Do not break a string with a backslash | +| [`forbidden-macro`](#forbidden-macro) | warning | on | — | Ban the macros your project has decided against | +| [`legacy-generate-region`](#legacy-generate-region) | style | off | — | Drop the `generate … endgenerate` wrapper | +| [`legacy-genvar-declaration`](#legacy-genvar-declaration) | style | off | — | Declare a genvar in the `for` header | +| [`macro-string-concatenation`](#macro-string-concatenation) | warning | off | — | Do not put `` `` `` in a plain string | +| [`module-begin-block`](#module-begin-block) | style | on | — | No `begin`/`end` at module scope | +| [`numeric-format-string-style`](#numeric-format-string-style) | style | off | — | Match a radix prefix to its specifier | +| [`positive-meaning-parameter-name`](#positive-meaning-parameter-name) | style | on | — | Name a parameter for what it enables | +| [`proper-parameter-declaration`](#proper-parameter-declaration) | style | off | — | `parameter` in a header, `localparam` in a body | +| [`suggest-parentheses`](#suggest-parentheses) | style | on | safe | Parenthesize a conditional inside a conditional | +| [`unpacked-dimensions-range-ordering`](#unpacked-dimensions-range-ordering) | style | on | — | Write an unpacked dimension `[0:N-1]` | +| [`uvm-macro-semicolon`](#uvm-macro-semicolon) | warning | off | — | No `;` after a `` `uvm_* `` macro | +| [`v2001-generate-begin`](#v2001-generate-begin) | style | on | — | No bare `begin` in a generate region | ## always-comb-blocking @@ -295,3 +314,79 @@ Reports a declaration whose type is an anonymous `enum`. The language gives no w ## 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. + +## create-object-name-match + +Reports a `::type_id::create("name", …)` whose string does not match the handle it is assigned to. That string is the object's UVM instance name, so every `uvm_config_db` path, factory override and `+uvm_set_config` plusarg written against the handle silently misses the object — and nothing fails, it just does not take. Only a plain variable target and a string-literal first argument are judged. Verible's `create-object-name-match`, same default. + +## dff-name-style + +Reports a nonblocking assignment in an `always_ff` whose target does not end in a registered-output suffix (`_q`, `_r`, `_ff`, `_reg`), one whose `_d`/`_n`/`_next` source does not share its base, and a name ending in one of those suffixes that is driven combinationally instead. Verible's `dff-name-style`, same default (off) and the same four options — `input`, `output`, `waive_ifs_with_conditions` and `waive_lhs_regex`, whose default is Verible's `(?i)mem.*` rewritten as `[mM][eE][mM].*` because lucisv's pattern engine has no inline flags. + +## disable-statement + +Reports `disable