Files
lucisv/crates/vlog_linter/src/rules/invalid_system_task_function.rs
T
lucioandClaude Fable 5 8adb6c8ac1 Linter expansion, wave 3: the remaining nineteen Verible rules, forbidden-macro, void-cast's forbidden calls, and the e2e options case
TODO section 35 (54 -> 73 rules: every rule in Verible's published
list but forbid-implicit-declarations).
module-begin-block, legacy-generate-region, legacy-genvar-declaration,
v2001-generate-begin, explicit-function-lifetime,
explicit-task-lifetime (both exempt out-of-body definitions after a
census showed 948 of 960 findings were exactly that shape),
positive-meaning-parameter-name, suggest-parentheses (safe fix,
truth-tabled), unpacked-dimensions-range-ordering, uvm-macro-semicolon,
create-object-name-match, numeric-format-string-style,
macro-string-concatenation, disable-statement, forbidden-macro,
endif-comment (safe fix), forbid-line-continuations, dff-name-style,
proper-parameter-declaration. Verible's forbidden-symbol is the
source-file name of invalid-system-task-function (read in its
rule .cc), so it is that rule's symbols option, nothing fires twice;
void-cast gains forbidden_calls. Shared readers: walk_items_scoped,
exprs.rs, preproc.rs. A checked-in e2e case drives lucisv.lint.options
over the wire. Two rules fire on an error leaf because the parser
refuses a module-scope begin/end and a bare generate begin - filed as
docs/topo.md 2.9-25.
3 695 tests / 48 binaries; corpus 814/820 byte-identical to 0.38.0;
opentitan default-set census 1 053 -> 1 169, the arithmetic balancing
to the six default-on additions; timing unchanged.

docs/features/linter-expansion-3/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 04:55:10 -05:00

199 lines
7.7 KiB
Rust

//! `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;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
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.
///
/// The `$dist_*` family and `$random` all draw from the *global* seed that
/// `$random` shares, so one extra call anywhere in a testbench reshuffles
/// every other stream; `$urandom` and `$urandom_range` are per-thread and
/// reproducible. `$psprintf` is a vendor extension for the standard
/// `$sformatf`, and `$srandom` seeds that same global generator rather than
/// the calling process.
const FORBIDDEN: &[(&str, &str)] = &[
("$psprintf", "$sformatf"),
("$random", "$urandom"),
("$srandom", "process::self().srandom()"),
("$dist_chi_square", "$urandom"),
("$dist_erlang", "$urandom"),
("$dist_exponential", "$urandom"),
("$dist_normal", "$urandom"),
("$dist_poisson", "$urandom"),
("$dist_t", "$urandom"),
("$dist_uniform", "$urandom"),
];
impl Rule for InvalidSystemTaskFunction {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not call a deprecated or non-reproducible system task"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn 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 \
every other random stream in it and a failing seed stops reproducing \
— the reason IEEE 1800 added the per-process `$urandom` / \
`$urandom_range` and `process::self().srandom()`. `$psprintf` is a \
vendor spelling of the standard `$sformatf` and is not portable. \
Verible's `invalid-system-task-function` (\"Checks that no forbidden \
system tasks or functions are used.\", enabled by default) forbids \
exactly this list, and lucisv names the replacement in the message.\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<Violation> {
let forbidden = ctx.option_list(NAME, "symbols");
ctx.tokens()
.iter()
.filter(|token| token.kind == TokenKind::SystemIdent)
.filter_map(|token| {
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()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
InvalidSystemTaskFunction.check(&LintContext::new(src, None))
}
#[test]
fn flags_every_forbidden_name_and_says_what_to_use() {
for (name, instead) in FORBIDDEN {
let src = format!("module m;\n initial x = {name}();\nendmodule\n");
let found = violations(&src);
assert_eq!(found.len(), 1, "{name}: {found:?}");
assert!(found[0].message.contains(name), "{}", found[0].message);
assert!(found[0].message.contains(instead), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], *name, "the call, underlined");
}
}
#[test]
fn the_replacements_and_their_neighbours_are_left_alone() {
let src = "module m;\n\
initial begin\n\
a = $urandom();\n\
b = $urandom_range(0, 7);\n\
c = $sformatf(\"%0d\", a);\n\
$display(\"%0d\", b);\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_near_miss_name_is_not_a_hit() {
// Matched whole, not by prefix: `$random_stable` and a signal called
// `random` are neither of them `$random`.
let src = "module m;\n\
logic random;\n\
initial begin\n\
a = $randomize_helper();\n\
b = random;\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_forbidden_name_inside_a_string_is_data() {
let src = "module m;\n initial $display(\"call $random here\");\nendmodule\n";
assert!(violations(src).is_empty());
}
/// 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());
}
}