TODO section 33. Every rule states a Severity (error: would likely fail
to compile or elaborate, or silently mis-synthesize; warning: a probable
bug; style), printed in lucisv check text and JSON, mapped to
ERROR/WARNING/INFORMATION in the editor, grouped in --rules-doc, and
accepted by --select/--ignore and [lint] as a class word. VS Code gains
lucisv.lint.severity.{error,warning,style} and one tri-state
lucisv.lint.rules.<rule> per rule (default/on/off - a client sends
every key, so a boolean cannot say unset), generated by
vlog_linter::vscode with a drift test, and lint::enabled_rules is the
one documented ladder: defaults -> select -> class switches -> per-rule
-> ignore. Nineteen new rules (17 -> 36), one file each with true
positives and near-misses: Error - mismatched-labels,
duplicate-declaration (Semantics::duplicates(), additive),
undeclared-identifier (with a project; silent for macro text, included
fragments, hierarchical tails, any name another file mentions),
unknown-port, unknown-parameter; Warning - forbid-defparam,
invalid-system-task-function, truncated-numeric-literal,
undersized-binary-literal (safe fix), suspicious-semicolon,
packed-dimensions-range-ordering, module-port, module-parameter,
explicit-function-task-parameter-type, plusarg-assignment,
instance-shadowing, forbid-negative-array-dim, void-cast,
incomplete-assignment. Every false-positive class found on opentitan
closed with a named test; 3 383 tests / 48 binaries; corpus 814/820
and byte-identical (formatter untouched); vsix smoke OK.
docs/features/linter-expansion-1/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
157 lines
5.5 KiB
Rust
157 lines
5.5 KiB
Rust
//! `truncated-numeric-literal` — a literal wider than the width it declares.
|
|
|
|
use crate::context::LintContext;
|
|
use crate::literal;
|
|
use crate::registry::Rule;
|
|
use crate::severity::Severity;
|
|
use crate::violation::Violation;
|
|
use vlog_parser::token::TokenKind;
|
|
|
|
/// See [`Rule::doc`].
|
|
pub struct TruncatedNumericLiteral;
|
|
|
|
const NAME: &str = "truncated-numeric-literal";
|
|
|
|
impl Rule for TruncatedNumericLiteral {
|
|
fn name(&self) -> &'static str {
|
|
NAME
|
|
}
|
|
|
|
fn summary(&self) -> &'static str {
|
|
"keep a sized literal inside the width it declares"
|
|
}
|
|
|
|
fn severity(&self) -> Severity {
|
|
Severity::Warning
|
|
}
|
|
|
|
fn doc(&self) -> &'static str {
|
|
"`4'hFFF` is not an error and not a warning in most simulators: the \
|
|
value is silently truncated to `4'hF` and the extra digits are gone. \
|
|
Whichever half of it was wrong — the width or the value — the code \
|
|
does not do what it reads as, and the reader has to count nibbles to \
|
|
see it. Verible's `truncated-numeric-literal` (\"Checks that numeric \
|
|
literals are not longer than their stated bit-width to avoid \
|
|
undesired accidental truncation.\", enabled by default) is the same \
|
|
rule. Leading zeros do not count (`8'h0FF` is eight bits), an `x` or \
|
|
`z` digit counts as a full digit, and a decimal literal carrying `x` \
|
|
is not judged at all. A literal whose digits are **all** unknown \
|
|
(`3'hz`, `7'hzz`) is left alone: those are how the language spells a \
|
|
three-bit and a seven-bit `z`, and their digit count only exceeds the \
|
|
width because a hex digit is four bits. No automatic fix: only the \
|
|
author knows which of the two numbers was meant."
|
|
}
|
|
|
|
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
|
ctx.tokens()
|
|
.iter()
|
|
.filter(|token| token.kind == TokenKind::Number)
|
|
.filter_map(|token| {
|
|
let parsed = literal::parse(&token.text)?;
|
|
let bits = parsed.significant_bits()?;
|
|
if bits <= parsed.width || all_unknown(&parsed.packed_digits()) {
|
|
return None;
|
|
}
|
|
Some(Violation::new(
|
|
NAME,
|
|
format!(
|
|
"literal needs {bits} bits but declares {}; the value is truncated",
|
|
parsed.width
|
|
),
|
|
token.span,
|
|
))
|
|
})
|
|
.collect()
|
|
}
|
|
}
|
|
|
|
/// True when every digit is `x`, `z` or `?`.
|
|
///
|
|
/// `3'hz` and `7'hzz` are how the language spells a three-bit and a seven-bit
|
|
/// `z`: the digit count exceeds the width by construction, because one hex
|
|
/// digit is four bits, and nothing is being truncated — the value is unknown
|
|
/// either way. Measured on opentitan, this shape was every one of the rule's
|
|
/// findings in `top_earlgrey/dv/tb/tb.sv`.
|
|
fn all_unknown(digits: &str) -> bool {
|
|
!digits.is_empty() && digits.chars().all(|c| matches!(c.to_ascii_lowercase(), 'x' | 'z' | '?'))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn violations(src: &str) -> Vec<Violation> {
|
|
TruncatedNumericLiteral.check(&LintContext::new(src, None))
|
|
}
|
|
|
|
fn assign(value: &str) -> String {
|
|
format!("module m;\n assign x = {value};\nendmodule\n")
|
|
}
|
|
|
|
#[test]
|
|
fn flags_a_literal_that_does_not_fit() {
|
|
let found = violations(&assign("4'hFFF"));
|
|
assert_eq!(found.len(), 1, "{found:?}");
|
|
assert!(found[0].message.contains("12 bits"), "{}", found[0].message);
|
|
assert!(found[0].message.contains("declares 4"), "{}", found[0].message);
|
|
assert!(found[0].fix.is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn flags_every_base() {
|
|
for value in ["1'b11", "2'o77", "4'hFF", "4'd16", "8'd300"] {
|
|
assert_eq!(violations(&assign(value)).len(), 1, "{value}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_literal_that_fits_is_silent() {
|
|
for value in [
|
|
"4'hF",
|
|
"4'h0F",
|
|
"8'h0FF",
|
|
"8'b0000_0001",
|
|
"32'hdead_beef",
|
|
"8'd255",
|
|
"4'h0",
|
|
"1'b0",
|
|
"8'sh7f",
|
|
] {
|
|
assert!(
|
|
violations(&assign(value)).is_empty(),
|
|
"{value}: {:?}",
|
|
violations(&assign(value))
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_unknown_digit_counts_but_a_decimal_unknown_is_not_judged() {
|
|
assert_eq!(violations(&assign("4'hxF")).len(), 1, "two nibbles in a one-nibble literal");
|
|
assert!(violations(&assign("4'hx")).is_empty(), "one nibble fits");
|
|
assert!(violations(&assign("8'dx")).is_empty(), "a decimal x says nothing about width");
|
|
}
|
|
|
|
/// `3'hz` is a three-bit `z`, not a truncated four-bit one — the shape
|
|
/// that was every opentitan finding in `top_earlgrey/dv/tb/tb.sv`.
|
|
#[test]
|
|
fn an_all_unknown_literal_is_not_truncated() {
|
|
for value in ["3'hz", "7'hzz", "1'bx", "5'h??", "3'hZ"] {
|
|
assert!(
|
|
violations(&assign(value)).is_empty(),
|
|
"{value}: {:?}",
|
|
violations(&assign(value))
|
|
);
|
|
}
|
|
// A mixed literal still counts its digits.
|
|
assert_eq!(violations(&assign("4'hxF")).len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn an_unsized_literal_and_a_plain_number_are_not_judged() {
|
|
for value in ["'h1f", "42", "1.5", "'0", "'1"] {
|
|
assert!(violations(&assign(value)).is_empty(), "{value}");
|
|
}
|
|
}
|
|
}
|