Files
lucisv/crates/vlog_linter/src/vscode.rs
T
lucioandClaude Fable 5 5e5813a2a9 Linter expansion, wave 2: per-rule options end to end, options on the naming rules, and eighteen Style rules
TODO section 34 (36 -> 54 rules).
Options: OptionSpec/OptionKind/OptionValue/RuleOptions in vlog_linter
with one validator behind both front ends - [lint.<rule>] tables in
lucisv.toml (accepted now; stored raw by lucisv_core::config, resolved
per file by the CLI with <config>:<line> on the first bad entry) and
the editor's lucisv.lint.options object (bad entries logged and
dropped) - precedence editor > toml > default key by key, --rules-doc
listing every option. A small anchored regex engine of our own: a
Thompson-NFA simulation, linear in pattern x name by construction
(QA's first cut found the backtracking matcher exponential on (a*)*b),
unknown escapes refused by name through both doors, a 71-row table
verified against CPython. The four naming rules take Verible's option
spellings with defaults that keep today's verdicts byte-identical.
Eighteen Style rules, one file each with true positives and near-
misses: line-length (the formatter's width), posix-eof (safe fix),
forbid-consecutive-null-statements (safe fix), generate-label and
generate-label-prefix, package-filename, one-module-per-file (off),
signal/interface/macro/constraint/parameter-type-name-style,
port-name-suffix (off), banned-declared-name-patterns (off),
typedef-enums, typedef-structs-unions (allow_anonymous_nested defaults
true here - opentitan's 3 159 findings were all generated register
packages, and its own config disables the rule), always-comb (unsafe
fix), explicit-begin (off, Verible's eleven enables). Four rules ask
parsed_cleanly() first after a census showed error-recovered UVM files
rebound as generate blocks. package.json regenerated (drift test).
3 549 tests / 48 binaries; corpus 814/820 byte-identical; naming-rule
finding lists identical to 0.36.0; opentitan check timing unchanged.

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

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:36:59 -05:00

231 lines
9.0 KiB
Rust

//! The VS Code lint settings, generated from the rule registry.
//!
//! `editors/vscode/package.json` declares one switch per severity class and
//! one per rule. Hand-written, that list would go stale the first time a rule
//! was added — the rule would ship with no way to turn it off from the
//! editor — so it is generated here instead, by the same crate that owns the
//! registry, exactly as [`crate::rules_markdown`] generates the rule
//! reference.
//!
//! Two consumers, one text: `cargo run -p vlog_linter --example
//! vscode_lint_settings` prints it for a human to paste in, and a test in
//! `lucisv_server` parses both this and `package.json` and fails when they
//! disagree. See `docs/features/linter-expansion-1/README.md`.
use crate::registry::all_rules;
use crate::severity::Severity;
use crate::Rule;
/// The setting a severity class's master switch is called.
pub fn severity_setting(severity: Severity) -> String {
format!("lucisv.lint.severity.{}", severity.as_str())
}
/// The setting one rule's toggle is called.
pub fn rule_setting(rule: &dyn Rule) -> String {
format!("lucisv.lint.rules.{}", rule.name())
}
/// The three words a per-rule toggle takes.
///
/// A tri-state rather than a boolean, and deliberately: the ladder in
/// `lucisv_server::settings::enabled_rules` distinguishes a rule the user
/// *said something about* from one they left alone, and a plain boolean cannot
/// carry that — a client sends every setting in the section, its default
/// included, so "unset" and "set to the default" would arrive identically and
/// a per-rule toggle would silently override `select` and the class switches.
pub const RULE_CHOICES: [&str; 3] = ["default", "on", "off"];
/// The whole `lucisv.lint.severity.*` + `lucisv.lint.rules.*` block, as the
/// JSON object `package.json`'s `configuration.properties` holds them in.
///
/// Two-space indentation with an eight-space margin, which is where those
/// properties sit in that file, so the text pastes in as it stands.
pub fn vscode_lint_settings() -> String {
let mut entries: Vec<String> = Vec::new();
for (i, severity) in Severity::ALL.into_iter().enumerate() {
entries.push(severity_entry(severity, 10 + i as u32));
}
let mut order = 20;
for severity in Severity::ALL {
for rule in all_rules().into_iter().filter(|rule| rule.severity() == severity) {
entries.push(rule_entry(rule, order));
order += 1;
}
}
format!("{{\n{}\n}}\n", entries.join(",\n"))
}
/// One class's master switch.
fn severity_entry(severity: Severity, order: u32) -> String {
let description = format!(
"Run the **{word}** lint rules — {what}. Turning this off silences the whole class; \
a per-rule toggle below still has the last word, and \
`#lucisv.lint.ignore#` still removes a rule whatever else says. \
Takes effect immediately — every open file is re-checked.",
word = severity.as_str(),
what = severity.describes(),
);
format!(
" \"{id}\": {{\n\
\x20 \"type\": \"boolean\",\n\
\x20 \"default\": true,\n\
\x20 \"order\": {order},\n\
\x20 \"markdownDescription\": {description}\n\
\x20 }}",
id = severity_setting(severity),
description = json_string(&description),
)
}
/// One rule's toggle.
fn rule_entry(rule: &'static dyn Rule, order: u32) -> String {
let description = format!(
"**{severity}** — {summary}. {default}{options}",
severity = rule.severity().as_str(),
summary = rule.summary(),
default = default_sentence(rule),
options = options_sentence(rule),
);
format!(
" \"{id}\": {{\n\
\x20 \"type\": \"string\",\n\
\x20 \"enum\": [{choices}],\n\
\x20 \"enumDescriptions\": [\n\
\x20 {leave},\n\
\x20 \"Always run this rule.\",\n\
\x20 \"Never run this rule.\"\n\
\x20 ],\n\
\x20 \"default\": \"default\",\n\
\x20 \"order\": {order},\n\
\x20 \"markdownDescription\": {description}\n\
\x20 }}",
id = rule_setting(rule),
choices = RULE_CHOICES.iter().map(|c| json_string(c)).collect::<Vec<_>>().join(", "),
leave = json_string(&format!("Leave it as it ships: {}", default_sentence(rule))),
description = json_string(&description),
)
}
/// The options a rule takes, named in its description.
///
/// No setting is generated *per option* — `lucisv.lint.options` is one object
/// that carries them all, and 60 more entries in the Settings UI would bury
/// the toggles this file exists to produce. What the description owes the
/// reader is the words to type into that object, which is this.
fn options_sentence(rule: &dyn Rule) -> String {
let names: Vec<String> = rule.options().iter().map(|spec| format!("`{}`", spec.name)).collect();
match names.len() {
0 => String::new(),
_ => format!(" Options (set them in `#lucisv.lint.options#`): {}.", names.join(", ")),
}
}
/// How a rule's own default is said in one sentence — the same three cases
/// [`crate::rules_markdown`]'s Default column spells.
fn default_sentence(rule: &dyn Rule) -> String {
match (rule.default_on(), rule.needs_workspace()) {
(true, _) => "On by default.".to_string(),
(false, true) => "On where lucisv can see the project.".to_string(),
(false, false) => "Off by default.".to_string(),
}
}
/// A JSON string literal. Hand-rolled, as the CLI's JSON output is: this crate
/// depends on `vlog_parser` and `std` alone, and a serialization framework for
/// one string shape is not a trade worth making.
fn json_string(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_rule_and_every_class_gets_an_entry() {
let json = vscode_lint_settings();
for severity in Severity::ALL {
assert!(json.contains(&format!("\"{}\"", severity_setting(severity))), "{severity:?}");
}
for rule in all_rules() {
let id = rule_setting(rule);
assert_eq!(json.matches(&format!("\"{id}\"")).count(), 1, "{id}");
assert!(
json.contains(&format!("**{}** — {}.", rule.severity().as_str(), rule.summary())),
"{id}: description",
);
}
}
/// The toggles are ordered worst class first, then by name — which is how
/// the Settings UI groups them.
#[test]
fn the_order_numbers_group_by_severity_then_name() {
let json = vscode_lint_settings();
let mut expected: Vec<String> = Vec::new();
for severity in Severity::ALL {
let mut names: Vec<&str> = all_rules()
.into_iter()
.filter(|rule| rule.severity() == severity)
.map(|rule| rule.name())
.collect();
names.sort_unstable();
expected.extend(names.into_iter().map(str::to_string));
}
let found: Vec<String> = json
.lines()
.filter_map(|line| line.trim().strip_prefix("\"lucisv.lint.rules."))
.filter_map(|rest| rest.split('"').next().map(str::to_string))
.collect();
assert_eq!(found, expected);
}
/// A rule with options says so, and names them; a rule without says
/// nothing extra.
#[test]
fn a_rules_description_names_the_options_it_takes() {
let json = vscode_lint_settings();
assert!(
json.contains("Options (set them in `#lucisv.lint.options#`): `length`."),
"line-length's option"
);
assert!(
json.contains(
"`localparam_style`, `localparam_style_regex`, `parameter_style`, \
`parameter_style_regex`."
),
"parameter-name-style's four"
);
for rule in all_rules() {
let has = !rule.options().is_empty();
let entry = json
.split(&format!("\"{}\"", rule_setting(rule)))
.nth(1)
.and_then(|rest| rest.split("},").next())
.unwrap_or_default();
assert_eq!(entry.contains("Options (set them in"), has, "{}", rule.name());
}
}
#[test]
fn json_strings_are_escaped() {
assert_eq!(json_string("a\"b\\c"), "\"a\\\"b\\\\c\"");
assert_eq!(json_string("em — dash"), "\"em — dash\"", "UTF-8 passes through");
}
}