887 lines
36 KiB
Rust
887 lines
36 KiB
Rust
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
|
|
|
//! The `lucisv check` driver: lint files, print diagnostics, apply fixes.
|
|
//!
|
|
//! Everything about *which* files are linted — the walk, `--exclude`,
|
|
//! `.gitignore`, config discovery — is the formatter's, unchanged: `check`
|
|
//! is handed the same `(path, config)` job list `format` gets. Only what
|
|
//! happens to one file differs.
|
|
|
|
use std::collections::HashMap;
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::ExitCode;
|
|
|
|
use lucisv_core::atomic::write_atomic;
|
|
use lucisv_core::config::FileConfig;
|
|
use rayon::prelude::*;
|
|
use vlog_formatter::fence::{self, Region};
|
|
use vlog_formatter::Config;
|
|
use vlog_linter::words;
|
|
use vlog_linter::{
|
|
apply_fixes, lint_with, ExternalWaivers, Fix, MentionOracle, ParsedSource, Rule, RuleOptions,
|
|
Violation, WaiverUse,
|
|
};
|
|
use vlog_parser::LineIndex;
|
|
|
|
use crate::args::{Options, OutputFormat};
|
|
|
|
/// How many fix-then-relint rounds one file gets. Two fixes that overlap
|
|
/// cannot both land in one pass (a tab that is also trailing whitespace is
|
|
/// the everyday case), so the loop runs until the file stops changing; the
|
|
/// cap only bounds a rule that would fight itself forever.
|
|
const MAX_FIX_ROUNDS: usize = 10;
|
|
|
|
/// One file to lint, with the rules the command line and its own
|
|
/// `lucisv.toml` resolved to.
|
|
pub struct Job {
|
|
path: PathBuf,
|
|
config: Config,
|
|
rules: Vec<&'static dyn Rule>,
|
|
/// What this file's `lucisv.toml` configured about each rule, validated
|
|
/// against the registry when the run was planned.
|
|
options: RuleOptions,
|
|
}
|
|
|
|
/// A whole `lucisv check` run: what to lint, and what the project says about
|
|
/// names.
|
|
pub struct Plan {
|
|
jobs: Vec<Job>,
|
|
/// The project's identifier census, built when at least one selected rule
|
|
/// asks for a workspace and there is more than one file to ask about.
|
|
census: Option<Census>,
|
|
/// Every external waiver file the run reads, applied to every job.
|
|
///
|
|
/// One set for the whole run rather than one per file, because a
|
|
/// `--location` pattern names files and a waiver is only *unused* when no
|
|
/// file in the run matched it — a question only the whole run can answer.
|
|
external: ExternalWaivers,
|
|
/// Every rule name any job in the run has switched on, for deciding which
|
|
/// external waivers never had a chance to fire.
|
|
enabled: Vec<&'static str>,
|
|
}
|
|
|
|
/// How many of the run's files write each identifier down.
|
|
///
|
|
/// The CLI's answer to the question the language server answers from its
|
|
/// index: it has none, so it builds one — a read and a lex of every file in
|
|
/// the run, before the first rule sees anything. Only the *counts* are kept;
|
|
/// a rule asks about one name at a time and never about a file.
|
|
pub struct Census {
|
|
files: HashMap<String, u32>,
|
|
/// Module or interface name → what it declares, `None` for a unit the run
|
|
/// cannot answer for: a header carrying a compiler directive, or two
|
|
/// declarations that disagree. Empty when no enabled rule asked for it —
|
|
/// building it costs a parse of every file in the run.
|
|
interfaces: HashMap<String, Option<vlog_linter::ModuleInterface>>,
|
|
/// Package name → the names it exports, `None` for a package the run
|
|
/// cannot answer for: one declared twice, or one re-exporting from
|
|
/// another package (only a whole-project index settles that). Empty
|
|
/// unless `unused-import` is enabled.
|
|
packages: HashMap<String, Option<Vec<String>>>,
|
|
}
|
|
|
|
/// What one file contributes to a [`Census`]: its words, the units it
|
|
/// declares, and the packages it exports from.
|
|
type PerFile = (
|
|
Vec<String>,
|
|
Vec<(String, Option<vlog_linter::ModuleInterface>)>,
|
|
Vec<(String, Option<Vec<String>>)>,
|
|
);
|
|
|
|
/// One file's three contributions, off **one** parse.
|
|
///
|
|
/// The word census wants the tokens, the interface table wants the tree and
|
|
/// the package table wants both — so a run that asks for either table lexes
|
|
/// and parses the file exactly once and all three read that. A run that asks
|
|
/// for neither never parses at all: `harvest_text` lexes and stops, which is
|
|
/// what the word census alone needs.
|
|
///
|
|
/// A file that cannot be read contributes nothing, and so does one that does
|
|
/// not lex (`harvest_text` and a `ParsedSource` with no tokens agree on that).
|
|
/// The file's own check is what reports the error.
|
|
fn harvest_one(job: &Job, interfaces: bool, packages: bool) -> PerFile {
|
|
let Ok(src) = std::fs::read_to_string(&job.path) else {
|
|
return (Vec::new(), Vec::new(), Vec::new());
|
|
};
|
|
if !interfaces && !packages {
|
|
return (words::harvest_text(&src), Vec::new(), Vec::new());
|
|
}
|
|
let parsed = ParsedSource::parse(&src);
|
|
let declared = match interfaces {
|
|
true => vlog_linter::module_interfaces(parsed.file()),
|
|
false => Vec::new(),
|
|
};
|
|
let exports = match packages {
|
|
true => vlog_linter::package_exports_in(&job.path, parsed.file(), parsed.tokens(), &src),
|
|
false => Vec::new(),
|
|
};
|
|
(words::harvest(parsed.tokens()), declared, exports)
|
|
}
|
|
|
|
impl Census {
|
|
/// The census of every file in the run, harvested in parallel.
|
|
///
|
|
/// A file that cannot be read or does not lex contributes nothing, which
|
|
/// is the same all-or-nothing rule the rest of the run gives it: the
|
|
/// file's own check reports the error.
|
|
///
|
|
/// `interfaces` says whether the run also needs each unit's ports and
|
|
/// parameters (`unknown-port`, `unknown-parameter`), and `packages`
|
|
/// whether it needs each package's exported names (`unused-import`).
|
|
/// Either costs a **parse** of every file on top of the lex the word
|
|
/// census already pays for, so each is built only when some enabled rule
|
|
/// asks — measured on opentitan `hw/` in
|
|
/// `docs/features/linter-expansion-1/README.md`.
|
|
fn of(jobs: &[Job], interfaces: bool, packages: bool) -> Census {
|
|
let per_file: Vec<PerFile> =
|
|
jobs.par_iter().map(|job| harvest_one(job, interfaces, packages)).collect();
|
|
|
|
let mut files: HashMap<String, u32> = HashMap::new();
|
|
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
|
|
let mut exported: HashMap<String, Option<Vec<String>>> = HashMap::new();
|
|
for (words, declared, exports) in per_file {
|
|
for word in words {
|
|
*files.entry(word).or_default() += 1;
|
|
}
|
|
// A package name the run declares twice is a package the run
|
|
// cannot answer for, whatever the two say — the same rule the
|
|
// workspace index applies, where two `units` is `Ambiguous`.
|
|
for (name, names) in exports {
|
|
exported.entry(name).and_modify(|held| *held = None).or_insert(names);
|
|
}
|
|
for (name, interface) in declared {
|
|
// Two declarations of one name answer only when they agree;
|
|
// anything else is a question the run cannot settle.
|
|
units
|
|
.entry(name)
|
|
.and_modify(|held| {
|
|
if *held != interface {
|
|
*held = None;
|
|
}
|
|
})
|
|
.or_insert(interface);
|
|
}
|
|
}
|
|
Census { files, interfaces: units, packages: exported }
|
|
}
|
|
|
|
/// How many files in the run write `name` down.
|
|
fn count(&self, name: &str) -> u32 {
|
|
self.files.get(name).copied().unwrap_or(0)
|
|
}
|
|
|
|
/// What the run says `name` declares, or `None` when it cannot say.
|
|
fn interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
|
|
self.interfaces.get(name)?.clone()
|
|
}
|
|
|
|
/// What the run says the package `name` exports.
|
|
fn package(&self, name: &str) -> vlog_linter::Exports {
|
|
match self.packages.get(name) {
|
|
Some(Some(names)) => vlog_linter::Exports::Known(names.clone()),
|
|
Some(None) => vlog_linter::Exports::Ambiguous,
|
|
None => vlog_linter::Exports::Unknown,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One file's view of the census: everything the project says, minus what
|
|
/// this file says about itself.
|
|
struct Elsewhere<'a> {
|
|
census: &'a Census,
|
|
/// This file's own words, sorted — [`words::harvest`]'s answer over the
|
|
/// tokens the file was linted from, so the subtraction is exact rather
|
|
/// than assumed.
|
|
own: Vec<String>,
|
|
}
|
|
|
|
impl MentionOracle for Elsewhere<'_> {
|
|
fn mentioned_elsewhere(&self, name: &str) -> bool {
|
|
let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok());
|
|
self.census.count(name) > mine
|
|
}
|
|
|
|
/// The run's interface table, which covers **every** file including this
|
|
/// one: a module is instantiated as often in the file that declares it as
|
|
/// anywhere else, and there is nothing to subtract here.
|
|
fn module_interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
|
|
self.census.interface(name)
|
|
}
|
|
|
|
/// The run's package table, whole-run for the same reason the interface
|
|
/// table is: a package is imported as often by the file that declares it
|
|
/// as by any other, and there is nothing here to subtract.
|
|
fn package_exports(&self, name: &str) -> vlog_linter::Exports {
|
|
self.census.package(name)
|
|
}
|
|
}
|
|
|
|
/// Resolve the run: the rules for each file, and whether a census is owed.
|
|
///
|
|
/// **Precedence is CLI over config, key by key**: `--select` replaces a
|
|
/// `[lint] select`, `--ignore` replaces a `[lint] ignore`, and a key the
|
|
/// command line does not mention is the config file's to answer — the same
|
|
/// ladder `--line-length` and `--indent` already climb.
|
|
///
|
|
/// A rule that [`Rule::needs_workspace`] is on by default here exactly when
|
|
/// the run holds more than one file: one file is one file whatever directory
|
|
/// it was found in, and a census of it could only ever say what the file
|
|
/// already says about itself.
|
|
pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Result<Plan, String> {
|
|
let workspace = gathered.len() > 1;
|
|
let external = external_waivers(opts, gathered.iter().map(|(_, _, file)| file))?;
|
|
let mut jobs = Vec::with_capacity(gathered.len());
|
|
for (path, config, file_config) in gathered {
|
|
let select = pick(&opts.select, file_config.lint_select.as_deref());
|
|
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
|
|
let rules = vlog_linter::select_rules(select, ignore, workspace)
|
|
.map_err(|e| format!("{}: {e}", path.display()))?;
|
|
let options = rule_options(&file_config)?;
|
|
jobs.push(Job { path, config, rules, options });
|
|
}
|
|
let asks = |wants: fn(&'static dyn Rule) -> bool| {
|
|
jobs.iter().any(|job| job.rules.iter().any(|rule| wants(*rule)))
|
|
};
|
|
let wanted = asks(|rule| rule.needs_workspace()) || asks(reads_packages);
|
|
let interfaces = asks(reads_interfaces);
|
|
let packages = asks(reads_packages);
|
|
let census = (workspace && wanted)
|
|
.then(|| Census::of(&jobs, workspace && interfaces, workspace && packages));
|
|
let mut enabled: Vec<&'static str> =
|
|
jobs.iter().flat_map(|job| job.rules.iter().map(|rule| rule.name())).collect();
|
|
enabled.sort_unstable();
|
|
enabled.dedup();
|
|
Ok(Plan { jobs, census, external, enabled })
|
|
}
|
|
|
|
/// The run's external waiver files, read once each: `--waiver-file` in flag
|
|
/// order, then every `[lint] waivers` entry of a config file governing an
|
|
/// input.
|
|
///
|
|
/// The two **add up** rather than override: a waiver file only ever suppresses
|
|
/// findings, so there is nothing for a command line to take back. A file named
|
|
/// twice over — the flag and a `lucisv.toml`, or one `lucisv.toml` governing
|
|
/// five hundred files — is read once, or its directives would each be reported
|
|
/// unused as many times as the file was read.
|
|
///
|
|
/// A file that cannot be read, or a directive that does not parse, fails the
|
|
/// run naming the file and the line, exactly as a bad `[lint.<rule>]` entry
|
|
/// does and for the same reason: a user wrote it and is watching.
|
|
pub fn external_waivers<'a>(
|
|
opts: &Options,
|
|
configs: impl Iterator<Item = &'a FileConfig>,
|
|
) -> Result<ExternalWaivers, String> {
|
|
let mut paths: Vec<PathBuf> = opts.waiver_files.iter().map(PathBuf::from).collect();
|
|
for config in configs {
|
|
for path in config.lint_waivers.iter().flatten() {
|
|
paths.push(path.clone());
|
|
}
|
|
}
|
|
let mut read: Vec<PathBuf> = Vec::new();
|
|
let mut waivers = ExternalWaivers::default();
|
|
for path in paths {
|
|
// Compared canonically, because the flag's path is relative to the
|
|
// working directory and a `lucisv.toml`'s is absolute: the same file
|
|
// named both ways is still one file, and reading it twice would report
|
|
// each of its dead directives twice. Only the *comparison* is
|
|
// canonical — the path a diagnostic names stays the one written.
|
|
let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
|
|
if read.contains(&key) {
|
|
continue;
|
|
}
|
|
let (file, problems) = ExternalWaivers::read(&path)?;
|
|
if let Some(problem) = problems.first() {
|
|
return Err(problem.clone());
|
|
}
|
|
waivers.absorb(file);
|
|
read.push(key);
|
|
}
|
|
Ok(waivers)
|
|
}
|
|
|
|
/// The `[lint.<rule>]` entries of one file's config, resolved against the
|
|
/// registry.
|
|
///
|
|
/// The names and the values are checked **here**, where the registry is, and
|
|
/// the first bad entry fails the run naming the config file and the line it
|
|
/// was written on — the same treatment a bad `[lint] select` name gets, and
|
|
/// for the same reason: a user typed it and is watching.
|
|
pub fn rule_options(file_config: &FileConfig) -> Result<RuleOptions, String> {
|
|
let mut options = RuleOptions::new();
|
|
for entry in &file_config.lint_options {
|
|
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
|
|
let file = file_config
|
|
.source
|
|
.as_ref()
|
|
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
|
|
// The rule is named as well as the option: the table header two
|
|
// lines up says which rule it is, and an error a user reads out
|
|
// of a CI log has no table header beside it.
|
|
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
|
|
})?;
|
|
}
|
|
Ok(options)
|
|
}
|
|
|
|
/// Whether this rule reads the census's **interface** half, which costs a
|
|
/// parse of every file in the run rather than a lex.
|
|
///
|
|
/// By name, because the alternative is a fourth boolean on the `Rule` trait
|
|
/// for two rules: `Rule::needs_workspace` already says "this rule asks the
|
|
/// project something", and which *question* it asks is between the rule and
|
|
/// the oracle. A name that is not in the registry cannot reach here — the
|
|
/// rules are `&'static dyn Rule` values from that registry — and a rule added
|
|
/// to the pair without being added here answers `None` and goes quiet, which
|
|
/// is the safe direction.
|
|
fn reads_interfaces(rule: &'static dyn Rule) -> bool {
|
|
matches!(rule.name(), "unknown-port" | "unknown-parameter")
|
|
}
|
|
|
|
/// The rule that reads the package table, which costs an index of every file
|
|
/// in the run on top of the word census.
|
|
fn reads_packages(rule: &'static dyn Rule) -> bool {
|
|
rule.name() == "unused-import"
|
|
}
|
|
|
|
/// The command line's list when it said anything, else the config file's.
|
|
pub(crate) fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
|
|
if cli.is_empty() {
|
|
config.unwrap_or(&[])
|
|
} else {
|
|
cli
|
|
}
|
|
}
|
|
|
|
/// What linting one file produced.
|
|
struct Report {
|
|
path: String,
|
|
/// Positions of the text the violations point into — which is the
|
|
/// *fixed* text when `--fix` rewrote the file.
|
|
index: LineIndex,
|
|
violations: Vec<Violation>,
|
|
/// Violations whose fix was applied and written back.
|
|
fixed: usize,
|
|
/// Which of the run's external waivers suppressed something in this file.
|
|
/// Merged across every file before the dead ones are reported.
|
|
used: WaiverUse,
|
|
/// Set when the file could not be fully checked: unreadable, unwritable,
|
|
/// or — because the lexer is all-or-nothing — unlexable, in which case
|
|
/// only the text-level rules saw it.
|
|
error: Option<String>,
|
|
}
|
|
|
|
/// Everything one file's lint pass reads besides the file itself.
|
|
///
|
|
/// One value rather than six parameters: every function below the driver
|
|
/// needs the same set, and the `--fix` loop passes it down another level
|
|
/// again.
|
|
struct Pass<'a> {
|
|
config: &'a Config,
|
|
rules: &'a [&'static dyn Rule],
|
|
options: &'a RuleOptions,
|
|
census: Option<&'a Census>,
|
|
/// The run's external waiver files. Empty unless `--waiver-file` or a
|
|
/// `[lint] waivers` named one, and then costing nothing.
|
|
external: &'a ExternalWaivers,
|
|
}
|
|
|
|
/// Lints every gathered file and reports. Exit 1 if anything is left over,
|
|
/// 2 if a file could not be read, written, or lexed.
|
|
pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
|
let mut reports: Vec<Report> = plan
|
|
.jobs
|
|
.par_iter()
|
|
.map(|job| {
|
|
let pass = Pass {
|
|
config: &job.config,
|
|
rules: &job.rules,
|
|
options: &job.options,
|
|
census: plan.census.as_ref(),
|
|
external: &plan.external,
|
|
};
|
|
check_one(&job.path, opts, &pass)
|
|
})
|
|
.collect();
|
|
// The dead external waivers are found once every file has been linted,
|
|
// and reported against the waiver file, which then sorts in among the
|
|
// sources like any other path.
|
|
reports.extend(dead_waivers(&plan.external, &reports, &plan.enabled));
|
|
// Diagnostics are printed sorted by path, then by position within the
|
|
// file (`lint` already sorts those), so a run over a directory reads
|
|
// top to bottom whatever order the walk or the worker pool produced.
|
|
reports.sort_by(|a, b| a.path.cmp(&b.path));
|
|
finish(opts, reports)
|
|
}
|
|
|
|
/// The `unused-waiver` reports for external waivers no file in the run used.
|
|
///
|
|
/// **After the whole run**, which is the whole reason this is the CLI's job
|
|
/// and not the linter's: a `--location` pattern may match a file the run has
|
|
/// not reached yet, so a waiver is only dead once every file has been asked.
|
|
fn dead_waivers(
|
|
external: &ExternalWaivers,
|
|
reports: &[Report],
|
|
enabled: &[&'static str],
|
|
) -> Vec<Report> {
|
|
if external.is_empty() {
|
|
return Vec::new();
|
|
}
|
|
let mut used = WaiverUse::default();
|
|
for report in reports {
|
|
used.merge(&report.used);
|
|
}
|
|
external
|
|
.unused(&used, enabled)
|
|
.into_iter()
|
|
.map(|dead| Report {
|
|
path: dead.path.display().to_string(),
|
|
index: LineIndex::new(&dead.text),
|
|
violations: dead.violations,
|
|
fixed: 0,
|
|
used: WaiverUse::default(),
|
|
error: None,
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Lints a buffer piped in on stdin. `--stdin-filename` names it, and is
|
|
/// what the rules that need a file name see.
|
|
pub fn check_stdin(
|
|
opts: &Options,
|
|
src: &str,
|
|
config: &Config,
|
|
rules: &[&'static dyn Rule],
|
|
options: &RuleOptions,
|
|
external: &ExternalWaivers,
|
|
) -> ExitCode {
|
|
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
|
|
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
|
|
let pass = Pass { config, rules, options, census: None, external };
|
|
let (violations, used, lex_error) = run_rules(src, path, &pass);
|
|
// Nothing is ever written back for stdin, so `--fix` has nothing to do
|
|
// here; the violations are reported as they are.
|
|
let error = lex_error.map(|e| format!("{name}: {e}"));
|
|
let report =
|
|
Report { path: name, index: LineIndex::new(src), violations, fixed: 0, used, error };
|
|
// One buffer is a whole run too, so a waiver that covered nothing in it is
|
|
// as dead as one that covered nothing in a directory.
|
|
let names: Vec<&'static str> = rules.iter().map(|rule| rule.name()).collect();
|
|
let mut reports = vec![report];
|
|
reports.extend(dead_waivers(external, &reports, &names));
|
|
finish(opts, reports)
|
|
}
|
|
|
|
/// Lints one file, optionally fixing it, and never panics out of its worker.
|
|
fn check_one(file: &Path, opts: &Options, pass: &Pass) -> Report {
|
|
let path = file.display().to_string();
|
|
let failed = |error: String| Report {
|
|
path: path.clone(),
|
|
index: LineIndex::new(""),
|
|
violations: Vec::new(),
|
|
fixed: 0,
|
|
used: WaiverUse::default(),
|
|
error: Some(error),
|
|
};
|
|
|
|
let src = match std::fs::read_to_string(file) {
|
|
Ok(s) => s,
|
|
Err(e) => return failed(format!("{path}: {e}")),
|
|
};
|
|
let outcome = crate::catch_panic(|| {
|
|
if opts.fix {
|
|
fix_source(&src, file, opts, pass)
|
|
} else {
|
|
let (violations, used, lex_error) = run_rules(&src, Some(file.to_path_buf()), pass);
|
|
(violations, used, None, 0, lex_error)
|
|
}
|
|
});
|
|
let (violations, used, rewritten, fixed, lex_error) = match outcome {
|
|
Ok(outcome) => outcome,
|
|
Err(msg) => return failed(format!("{path}: panicked while linting: {msg}")),
|
|
};
|
|
let index = LineIndex::new(rewritten.as_deref().unwrap_or(&src));
|
|
if let Some(text) = rewritten {
|
|
if let Err(e) = write_atomic(file, text.as_bytes()) {
|
|
return failed(format!("{path}: {e}"));
|
|
}
|
|
}
|
|
// A file that does not lex still gets its text-level findings — those
|
|
// rules ran — but every token- and AST-level rule silently saw nothing,
|
|
// so the file must not pass as checked. It is an error (exit 2), exactly
|
|
// as `lucisv format` treats the same file.
|
|
let error = lex_error.map(|e| format!("{path}: {e}"));
|
|
Report { path, index, violations, fixed, used, error }
|
|
}
|
|
|
|
/// Runs the rules over one text, reporting which external waivers fired. The
|
|
/// last part of the answer is the lex error when the text does not lex —
|
|
/// rendered `line:col: message`, ready for a path prefix — because a file with
|
|
/// no tokens was only text-linted and must be reported as an error, not passed
|
|
/// off as clean.
|
|
fn run_rules(
|
|
src: &str,
|
|
path: Option<PathBuf>,
|
|
pass: &Pass,
|
|
) -> (Vec<Violation>, WaiverUse, Option<String>) {
|
|
let Pass { config, rules, options, census, external } = *pass;
|
|
// One parse per file (TODO §4): the products are built here, once, and
|
|
// lent to the context. Under `--fix` each *round* re-enters through this
|
|
// function with rewritten text — that re-parse is inherent (the old
|
|
// products describe text that no longer exists), so only the first round
|
|
// saves a parse; a plain `lucisv check` always does.
|
|
let parsed = ParsedSource::parse(src);
|
|
let lex_error = parsed.lex_error().map(|e| format!("lex error: {e}"));
|
|
// This file's own words, off the tokens it was just lexed from rather
|
|
// than off a second lex — what the oracle subtracts from the project's
|
|
// census so a signal never counts as mentioned by its own declaration.
|
|
let elsewhere = census.map(|census| Elsewhere { census, own: words::harvest(parsed.tokens()) });
|
|
// The indent width the formatter would use is also the width a tab
|
|
// expands to, so `--indent 4` fixes tabs into four spaces — and the width
|
|
// it would wrap to is the width `line-length` holds the file to.
|
|
let ctx = parsed
|
|
.context(path)
|
|
.with_tab_width(config.indent_width)
|
|
.with_line_length(config.max_width)
|
|
.with_options(options);
|
|
let ctx = match &elsewhere {
|
|
Some(elsewhere) => ctx.with_oracle(elsewhere),
|
|
None => ctx,
|
|
};
|
|
let (violations, used) = lint_with(&ctx, rules, external);
|
|
(violations, used, lex_error)
|
|
}
|
|
|
|
/// The violations whose fix may be applied: everything except a fix that
|
|
/// would edit bytes inside a `// verilog_format: off` region.
|
|
///
|
|
/// `off` means hands-off across both tools. The formatter emits a fenced
|
|
/// region as the exact source bytes it was written with; a linter that
|
|
/// rewrote those same bytes would make the fence a promise only half of lucisv
|
|
/// keeps. The violation is still **reported** — a finding is information, and
|
|
/// silencing it is what waivers are for — it just loses its automatic fix.
|
|
///
|
|
/// Which bytes count as fenced is [`fence::protected_regions`]' answer, not
|
|
/// one of this file's own: the language server asks the same question about
|
|
/// the same buffers, and two answers to it would drift.
|
|
fn fixable_outside_fences(text: &str, violations: &[Violation]) -> Vec<Violation> {
|
|
let regions = fence::protected_regions(text);
|
|
if regions.is_empty() {
|
|
return violations.to_vec();
|
|
}
|
|
violations
|
|
.iter()
|
|
.filter(|violation| violation.fix.as_ref().is_some_and(|fix| !touches_fence(fix, ®ions)))
|
|
.cloned()
|
|
.collect()
|
|
}
|
|
|
|
/// True when any edit of `fix` overlaps a fenced region.
|
|
fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
|
fix.edits
|
|
.iter()
|
|
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
|
|
}
|
|
|
|
/// Applies fixes until the file stops changing. Returns what is left over,
|
|
/// the rewritten text (if it changed) and how many fixes landed.
|
|
fn fix_source(
|
|
src: &str,
|
|
file: &Path,
|
|
opts: &Options,
|
|
pass: &Pass,
|
|
) -> (Vec<Violation>, WaiverUse, Option<String>, usize, Option<String>) {
|
|
let mut text = src.to_string();
|
|
let mut fixed = 0;
|
|
let mut used = WaiverUse::default();
|
|
let (mut violations, mut round_used, mut lex_error) =
|
|
run_rules(&text, Some(file.to_path_buf()), pass);
|
|
used.merge(&round_used);
|
|
for _ in 0..MAX_FIX_ROUNDS {
|
|
let round =
|
|
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
|
|
if round.applied == 0 {
|
|
break;
|
|
}
|
|
fixed += round.applied;
|
|
text = round.output;
|
|
(violations, round_used, lex_error) = run_rules(&text, Some(file.to_path_buf()), pass);
|
|
// A waiver that covered a finding in an earlier round did its job even
|
|
// though the fix then removed the finding, so usage accumulates over
|
|
// the rounds rather than being the last round's.
|
|
used.merge(&round_used);
|
|
}
|
|
let rewritten = (text != src).then_some(text);
|
|
(violations, used, rewritten, fixed, lex_error)
|
|
}
|
|
|
|
/// Prints the run and turns it into an exit code.
|
|
fn finish(opts: &Options, reports: Vec<Report>) -> ExitCode {
|
|
let violations: usize = reports.iter().map(|r| r.violations.len()).sum();
|
|
let fixed: usize = reports.iter().map(|r| r.fixed).sum();
|
|
let errors = reports.iter().filter(|r| r.error.is_some()).count();
|
|
|
|
match opts.output_format {
|
|
OutputFormat::Text => print_text(&reports),
|
|
OutputFormat::Json => print_json(&reports),
|
|
}
|
|
for report in &reports {
|
|
// Errors go to stderr in both formats, so `--output-format json`
|
|
// emits one parsable array and nothing else on stdout.
|
|
if let Some(error) = &report.error {
|
|
eprintln!("error: {error}");
|
|
}
|
|
}
|
|
summarize(violations, fixed, errors);
|
|
|
|
if errors > 0 {
|
|
ExitCode::from(2)
|
|
} else if violations > 0 {
|
|
ExitCode::from(1)
|
|
} else {
|
|
ExitCode::SUCCESS
|
|
}
|
|
}
|
|
|
|
/// Verible's diagnostic line with the severity word in front of the message:
|
|
/// `FILE:LINE:COL: error|warning|style: message [rule-name]`.
|
|
///
|
|
/// The word sits where a compiler puts it, so the line greps and reads the way
|
|
/// every other tool's does, and `grep ': error:'` is the whole of "show me
|
|
/// what would not compile".
|
|
fn print_text(reports: &[Report]) {
|
|
let mut out = String::new();
|
|
for report in reports {
|
|
for violation in &report.violations {
|
|
let (line, col) = position(report, violation);
|
|
out.push_str(&format!(
|
|
"{}:{line}:{col}: {}: {} [{}]\n",
|
|
report.path,
|
|
violation.severity.as_str(),
|
|
violation.message,
|
|
violation.rule
|
|
));
|
|
}
|
|
}
|
|
print!("{out}");
|
|
}
|
|
|
|
/// One JSON array of diagnostics, ruff-shaped: enough to drive an editor
|
|
/// without reading the text output back.
|
|
fn print_json(reports: &[Report]) {
|
|
let mut items = Vec::new();
|
|
for report in reports {
|
|
for violation in &report.violations {
|
|
let (line, col) = position(report, violation);
|
|
let (end_line, end_col) = end_position(report, violation);
|
|
items.push(format!(
|
|
"{{\"filename\":{},\"rule\":{},\"severity\":{},\"message\":{},\
|
|
\"location\":{{\"line\":{line},\"column\":{col}}},\
|
|
\"end_location\":{{\"line\":{end_line},\"column\":{end_col}}},\
|
|
\"range\":{{\"start\":{},\"end\":{}}},\"fix\":{}}}",
|
|
quote(&report.path),
|
|
quote(violation.rule),
|
|
quote(violation.severity.as_str()),
|
|
quote(&violation.message),
|
|
violation.span.start,
|
|
violation.span.end,
|
|
fix_json(violation),
|
|
));
|
|
}
|
|
}
|
|
println!("[{}]", items.join(","));
|
|
}
|
|
|
|
fn fix_json(violation: &Violation) -> String {
|
|
let Some(fix) = &violation.fix else { return "null".to_string() };
|
|
let edits = fix
|
|
.edits
|
|
.iter()
|
|
.map(|(range, content)| {
|
|
format!(
|
|
"{{\"start\":{},\"end\":{},\"content\":{}}}",
|
|
range.start,
|
|
range.end,
|
|
quote(content)
|
|
)
|
|
})
|
|
.collect::<Vec<_>>();
|
|
format!(
|
|
"{{\"applicability\":{},\"edits\":[{}]}}",
|
|
quote(fix.applicability.as_str()),
|
|
edits.join(",")
|
|
)
|
|
}
|
|
|
|
/// A JSON string literal. Hand-rolled: the shape is three fields deep and
|
|
/// pulling in a serialization framework for it is not a trade worth making.
|
|
pub(crate) fn quote(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
|
|
}
|
|
|
|
/// 1-based line and column of a diagnostic's start.
|
|
fn position(report: &Report, violation: &Violation) -> (u32, u32) {
|
|
report.index.line_col(violation.span.start)
|
|
}
|
|
|
|
/// 1-based line and column one past a diagnostic's last byte.
|
|
fn end_position(report: &Report, violation: &Violation) -> (u32, u32) {
|
|
report.index.line_col(violation.span.end)
|
|
}
|
|
|
|
fn summarize(violations: usize, fixed: usize, errors: usize) {
|
|
let mut summary = Vec::new();
|
|
if violations > 0 {
|
|
summary.push(format!("found {violations} violation{}", plural(violations)));
|
|
}
|
|
if fixed > 0 {
|
|
summary.push(format!("fixed {fixed} violation{}", plural(fixed)));
|
|
}
|
|
if errors > 0 {
|
|
summary.push(format!("{errors} file{} could not be checked", plural(errors)));
|
|
}
|
|
if !summary.is_empty() {
|
|
eprintln!("{}", summary.join(", "));
|
|
}
|
|
}
|
|
|
|
fn plural(n: usize) -> &'static str {
|
|
if n == 1 {
|
|
""
|
|
} else {
|
|
"s"
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
use vlog_linter::{Fix as LintFix, Violation as LintViolation};
|
|
use vlog_parser::span::TextRange;
|
|
|
|
/// A region covering bytes 10..20, as `fence::collect` would report one.
|
|
fn region() -> Vec<Region> {
|
|
vec![Region { fence: 10, start: 10, end: 20 }]
|
|
}
|
|
|
|
fn edit_at(start: u32, end: u32) -> LintFix {
|
|
LintFix::safe(vec![(TextRange::new(start, end), "x".to_string())])
|
|
}
|
|
|
|
#[test]
|
|
fn a_fix_is_blocked_exactly_at_the_fence_boundaries() {
|
|
let regions = region();
|
|
// First byte inside, last byte inside, and the whole span.
|
|
assert!(touches_fence(&edit_at(10, 11), ®ions), "first byte inside");
|
|
assert!(touches_fence(&edit_at(19, 20), ®ions), "last byte inside");
|
|
assert!(touches_fence(&edit_at(10, 20), ®ions), "the whole region");
|
|
// Adjacent on both ends, touching nothing inside.
|
|
assert!(!touches_fence(&edit_at(9, 10), ®ions), "ends where the region starts");
|
|
assert!(!touches_fence(&edit_at(20, 21), ®ions), "starts where the region ends");
|
|
// Straddling either edge is still a hit.
|
|
assert!(touches_fence(&edit_at(9, 11), ®ions), "straddles the start");
|
|
assert!(touches_fence(&edit_at(19, 21), ®ions), "straddles the end");
|
|
// An insertion (empty range) inside must not be spliced in either,
|
|
// while one at the far edge is outside.
|
|
assert!(touches_fence(&edit_at(15, 15), ®ions), "insertion inside");
|
|
assert!(touches_fence(&edit_at(10, 10), ®ions), "insertion at the first byte");
|
|
assert!(!touches_fence(&edit_at(20, 20), ®ions), "insertion just past the end");
|
|
}
|
|
|
|
#[test]
|
|
fn a_multi_edit_fix_is_blocked_if_any_edit_lands_inside() {
|
|
let fix = LintFix::safe(vec![
|
|
(TextRange::new(0, 1), "x".to_string()),
|
|
(TextRange::new(15, 16), "y".to_string()),
|
|
]);
|
|
assert!(touches_fence(&fix, ®ion()), "one edit inside blocks the whole fix");
|
|
}
|
|
|
|
#[test]
|
|
fn fixes_outside_a_fence_survive_the_filter() {
|
|
// Line 2 is fenced, line 4 is not; both have a tab worth fixing.
|
|
let text = "module m;\n// lucisv: off\n\ta = 1;\n// lucisv: on\n\tb = 2;\nendmodule\n";
|
|
let fenced = text.find("\ta = 1").unwrap_or(0) as u32;
|
|
let free = text.find("\tb = 2").unwrap_or(0) as u32;
|
|
let violations = vec![
|
|
LintViolation::new("no-tabs", "tab", TextRange::new(fenced, fenced + 1))
|
|
.with_fix(edit_at(fenced, fenced + 1)),
|
|
LintViolation::new("no-tabs", "tab", TextRange::new(free, free + 1))
|
|
.with_fix(edit_at(free, free + 1)),
|
|
];
|
|
let kept = fixable_outside_fences(text, &violations);
|
|
assert_eq!(kept.len(), 1, "only the unfenced fix survives");
|
|
assert_eq!(kept[0].span.start, free);
|
|
}
|
|
|
|
#[test]
|
|
fn a_file_without_fences_keeps_every_fix() {
|
|
let text = "module m;\n\ta = 1;\nendmodule\n";
|
|
let violations =
|
|
vec![LintViolation::new("no-tabs", "tab", TextRange::new(10, 11))
|
|
.with_fix(edit_at(10, 11))];
|
|
assert_eq!(fixable_outside_fences(text, &violations).len(), 1);
|
|
}
|
|
|
|
/// One `no-tabs`-shaped violation over the tab at `at`.
|
|
fn tab_violation(at: usize) -> Vec<LintViolation> {
|
|
let at = at as u32;
|
|
vec![LintViolation::new("no-tabs", "tab", TextRange::new(at, at + 1))
|
|
.with_fix(edit_at(at, at + 1))]
|
|
}
|
|
|
|
#[test]
|
|
fn the_line_scan_backstops_a_file_that_does_not_parse() {
|
|
// Error recovery can swallow the structure `fence::collect` hangs a
|
|
// region on; the union's scan half still finds it. Owned by
|
|
// `fence::protected_regions` now — this is the CLI end of it.
|
|
let text = "module m;\n@@@ junk;\n// lucisv: off\n\ta = 1;\n// lucisv: on\nendmodule\n";
|
|
let tab = text.find("\ta = 1").unwrap_or(0);
|
|
assert!(fixable_outside_fences(text, &tab_violation(tab)).is_empty(), "declined");
|
|
}
|
|
|
|
#[test]
|
|
fn an_unclosed_fence_runs_to_the_end_of_the_file() {
|
|
let text = "module m;\n// lucisv: off\n\ta = 1;\nendmodule\n";
|
|
let tab = text.find("\ta = 1").unwrap_or(0);
|
|
assert!(fixable_outside_fences(text, &tab_violation(tab)).is_empty(), "declined");
|
|
}
|
|
|
|
#[test]
|
|
fn an_ordinary_comment_is_not_a_fence() {
|
|
for text in [
|
|
"module m;\n// lucisv: off-by-one\n\ta = 1;\nendmodule\n",
|
|
"module m;\n// just a note\n\ta = 1;\nendmodule\n",
|
|
// A stray `on` opens nothing.
|
|
"module m;\n// lucisv: on\n\ta = 1;\nendmodule\n",
|
|
] {
|
|
let tab = text.find("\ta = 1").unwrap_or(0);
|
|
assert_eq!(fixable_outside_fences(text, &tab_violation(tab)).len(), 1, "{text:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn json_strings_are_escaped() {
|
|
assert_eq!(quote("plain"), "\"plain\"");
|
|
assert_eq!(quote("a\"b\\c"), "\"a\\\"b\\\\c\"");
|
|
assert_eq!(quote("tab\there"), "\"tab\\there\"");
|
|
assert_eq!(quote("bell\u{7}"), "\"bell\\u0007\"");
|
|
}
|
|
}
|
|
|
|
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|