Files
lucisv/crates/vlog_linter/src/rules/macro_string_concatenation.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

162 lines
5.6 KiB
Rust

//! `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<Violation> {
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<usize> {
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<usize> {
(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<Violation> {
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));
}
}