Files
lucisv/crates/lucisv_core/src/config.rs
T
lucioandClaude Fable 5.1 a69a1cb528 Coverage gaps L3, L6, L10: six language shapes, randsequence as real nodes, an opt-in uvm_field_* indent
TODO §54 (docs/features/coverage-gaps-l); closes docs/coverage_gaps.md
L3, L6 and L10. The first dev stalled under machine load; a second
finished from the tree.

54.1 `->>` with optional delay or event control (`StmtKind::EventTrigger`),
stream `with [range]` (`ExprKind::StreamWith`), the LRM's other
`casting_type`s, drive strength on a net declaration (`DataDecl::strength`,
whose comment slots also fix a pre-existing refusal on an `assign` with
a comment before its strength), `let` at statement position
(`StmtKind::Let`), and `#(min:typ:max)` clocking skews — `ClockingSkew`
as the LRM's two alternatives, `edge [delay]` | `delay` (review rework of
QA's HIGH). Comment slots added to `let`, stream concatenations and the
clocking grammar; the RTL gap fuzzer at 505 gaps, zero failing.
54.2 `randsequence` (it was a parse error; the keyword is new):
`RandSequence` → `Production` → `Alternative` → `ProdItem` (ref, block,
if, repeat, case, rand join), code blocks by the statement grammar; one
production per line, alternatives aligned; the LRM's examples as cases.
54.3 `[format] uvm-utils-indent` / `lucisv.format.uvmUtilsIndent`, default
off, tracking nested `_begin`/`_end` pairs; 21 corpus files change with
it on, all idempotent. A short comment-free enum body already one-lines,
so no key was built — the behaviour is pinned. `[format]` table tests
added (review rework). `->>`'s event control is bound through the shared
`bind_timing` (review rework of QA's second HIGH).

0 of 820 corpus files differ from 0.48.x with the key off; the opentitan
sweep is identical; no corpus or opentitan file writes any of the new
shapes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:12:49 -05:00

940 lines
38 KiB
Rust

//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
//!
//! Only what a small config file needs is supported (comments, `key = int`,
//! `key = "string"`, `key = ["a", "b"]`, the table `[lint]` and the per-rule
//! `[lint.<rule>]` tables); everything else is rejected by name rather than
//! ignored. See
//! `docs/features/config-discovery/README.md` for the grammar and the
//! reasoning behind not taking a TOML dependency.
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
/// Config file names, in the order a directory is probed.
const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
/// The settings one config file carries. Every key is optional; an unset
/// key leaves the CLI flag (or the built-in default) in charge.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct FileConfig {
/// `line-length`: maximum line width.
pub line_length: Option<usize>,
/// `indent`: indent width in spaces.
pub indent: Option<usize>,
/// `exclude`: patterns appended to the CLI's `--exclude` list.
pub exclude: Option<Vec<String>>,
/// `filelist`: the `.f` file naming the project's sources.
///
/// [`parse`] records it exactly as written, since it has no idea where
/// the config file lives; [`Discovery`] resolves it against that file's
/// directory, so every `FileConfig` a `Discovery` hands out carries a
/// usable path. See `docs/features/filelist/README.md`.
pub filelist: Option<PathBuf>,
/// `[format] uvm-utils-indent`: indent the `` `uvm_field_* `` macro
/// statements written between `` `uvm_*_utils_begin `` and
/// `` `uvm_*_utils_end ``. Off for the same reason.
pub format_uvm_utils_indent: Option<bool>,
/// `[lint] select`: run exactly these rules, replacing the default set.
/// The names are **not** validated here — this crate does not know the
/// rule registry; `lucisv check` validates them the moment it resolves the
/// run's rules, with the same error a bad `--select` gets.
pub lint_select: Option<Vec<String>>,
/// `[lint] ignore`: rules dropped from whatever `select` left.
pub lint_ignore: Option<Vec<String>>,
/// `[lint] waivers`: external waiver files, in the order written.
///
/// Like [`FileConfig::filelist`], these name *other files*: [`parse`]
/// records them exactly as written and [`Discovery`] resolves each one
/// against the config file's own directory, so every `FileConfig` a
/// `Discovery` hands out carries usable paths. Nothing here reads them —
/// their contents name lint rules, and this crate does not know the rule
/// registry any more than it does for `select`.
pub lint_waivers: Option<Vec<PathBuf>>,
/// `[lint.<rule>]` tables, **as written**: one entry per key, in file
/// order.
///
/// Neither the rule names nor the option names or their values are
/// checked here — this crate does not know the rule registry, exactly as
/// it does not know which rule names `select` may hold. `lucisv check`
/// resolves them against `vlog_linter`'s specs and fails the run naming
/// this file and the line, which is what [`LintOption::line`] is for.
pub lint_options: Vec<LintOption>,
/// The config file these settings were read from, when they were read
/// from one. `parse` leaves it unset — it is handed text, not a path —
/// and [`Discovery`] fills it in, so an error about an entry can name the
/// file the user has to edit.
pub source: Option<PathBuf>,
}
/// One `key = value` written under a `[lint.<rule>]` table, as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintOption {
/// The rule named by the table header.
pub rule: String,
/// The option key.
pub key: String,
/// The value's text, comment stripped, quotes and all — the linter's own
/// parser reads it, because only it knows what kind the key takes.
pub raw: String,
/// 1-based line the entry was written on.
pub line: usize,
}
/// Parses the supported TOML subset. Errors are prefixed `<line>: ` so the
/// caller can render them as `file:line: message`.
pub fn parse(text: &str) -> Result<FileConfig, String> {
let mut config = FileConfig::default();
// Editors on some platforms prepend a BOM; it would otherwise garble
// key matching on line 1 into an `unknown key` with invisible cause.
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
// Which table the keys below belong to: the top level until a header
// opens one, and then that one until the next header. Nothing closes a
// table, which is TOML's own rule.
let mut table = Table::Top;
for (index, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
parse_entry(line, &mut config, &mut table, index + 1)
.map_err(|e| format!("{}: {e}", index + 1))?;
}
Ok(config)
}
/// The table whose keys are being read.
enum Table {
/// Before any header: the formatter's own keys.
Top,
/// `[lint]`: `select`, `ignore` and `waivers`.
Lint,
/// `[format]`: the layout keys that are off by default.
Format,
/// `[lint.<rule>]`: that rule's options.
Rule(String),
}
fn parse_entry(
line: &str,
config: &mut FileConfig,
table: &mut Table,
number: usize,
) -> Result<(), String> {
if line.starts_with('[') {
// `[lint]` carries `select`/`ignore`/`waivers`; `[lint.<rule>]` carries that
// rule's options, which are stored raw and checked by whoever knows
// the registry.
if line == "[lint]" {
*table = Table::Lint;
return Ok(());
}
if line == "[format]" {
*table = Table::Format;
return Ok(());
}
if let Some(rule) = line.strip_prefix("[lint.").and_then(|r| r.strip_suffix(']')) {
if rule.is_empty() || rule.contains('.') || rule.contains(' ') {
return Err(format!("`{line}` is not a rule table; write `[lint.<rule-name>]`"));
}
*table = Table::Rule(rule.to_string());
return Ok(());
}
return Err(format!(
"unknown table `{line}` \
(the tables are `[format]`, `[lint]` and `[lint.<rule-name>]`)"
));
}
let (key, value) =
line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?;
let key = key.trim();
let value = strip_comment(value.trim());
if value.is_empty() {
return Err(format!("`{key}` has no value"));
}
match table {
Table::Format => return parse_format_entry(key, value, config),
Table::Lint => return parse_lint_entry(key, value, config),
Table::Rule(rule) => return parse_rule_entry(rule, key, value, config, number),
Table::Top => {}
}
match key {
"line-length" => set_int(&mut config.line_length, key, value, 40, 400),
"indent" => set_int(&mut config.indent, key, value, 1, 8),
"exclude" => {
if config.exclude.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.exclude = Some(parse_array(value)?);
Ok(())
}
"filelist" => {
if config.filelist.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.filelist = Some(PathBuf::from(parse_string(value)?));
Ok(())
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
uvm-utils-indent under `[format]`; \
select, ignore, waivers under `[lint]`; and a rule's own options \
under `[lint.<rule-name>]`)"
)),
}
}
/// One key of the `[format]` table: a boolean that defaults to off, because
/// it changes how already-clean files are laid out and a project has to opt
/// in before anything of its moves.
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
let slot = match key {
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
_ => {
return Err(format!(
"unknown key `{key}` under `[format]` \
(the only key is uvm-utils-indent)"
))
}
};
if slot.is_some() {
return Err(format!("duplicate key `{key}`"));
}
*slot = Some(parse_bool(key, value)?);
Ok(())
}
/// `true` or `false`, and nothing else — a misspelling is a typo the user
/// wants to hear about, not a silent `false`.
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
match value {
"true" => Ok(true),
"false" => Ok(false),
_ => Err(format!("`{key}` expects `true` or `false`, found `{value}`")),
}
}
/// One key of the `[lint]` table.
fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
if key == "waivers" {
if config.lint_waivers.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.lint_waivers = Some(parse_array(value)?.into_iter().map(PathBuf::from).collect());
return Ok(());
}
let slot = match key {
"select" => &mut config.lint_select,
"ignore" => &mut config.lint_ignore,
_ => {
return Err(format!(
"unknown key `{key}` under `[lint]` (known keys: select, ignore, waivers)"
))
}
};
if slot.is_some() {
return Err(format!("duplicate key `{key}`"));
}
*slot = Some(parse_array(value)?);
Ok(())
}
/// One `key = value` of a `[lint.<rule>]` table, kept as written.
fn parse_rule_entry(
rule: &str,
key: &str,
value: &str,
config: &mut FileConfig,
line: usize,
) -> Result<(), String> {
if config.lint_options.iter().any(|held| held.rule == rule && held.key == key) {
return Err(format!("duplicate key `{key}` under `[lint.{rule}]`"));
}
config.lint_options.push(LintOption {
rule: rule.to_string(),
key: key.to_string(),
raw: value.to_string(),
line,
});
Ok(())
}
fn set_int(
slot: &mut Option<usize>,
key: &str,
value: &str,
low: usize,
high: usize,
) -> Result<(), String> {
if slot.is_some() {
return Err(format!("duplicate key `{key}`"));
}
// The documented grammar is `digit+`; Rust's from_str also accepts a
// leading `+`, which we reject to keep the grammar honest.
if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
return Err(format!("`{key}` expects an integer, found `{value}`"));
}
let n: usize =
value.parse().map_err(|_| format!("`{key}` expects an integer, found `{value}`"))?;
if n < low || n > high {
return Err(format!("`{key}` must be between {low} and {high}, found {n}"));
}
*slot = Some(n);
Ok(())
}
fn parse_array(value: &str) -> Result<Vec<String>, String> {
let inner = value
.strip_prefix('[')
.and_then(|rest| rest.strip_suffix(']'))
.ok_or("multi-line arrays are unsupported in lucisv.toml; write `[ \"a\", \"b\" ]`")?;
let mut items: Vec<&str> = inner.split(',').map(str::trim).collect();
if items.last() == Some(&"") {
// Either an empty array or a permitted trailing comma.
items.pop();
}
items.iter().map(|item| parse_string(item)).collect()
}
fn parse_string(value: &str) -> Result<String, String> {
let inner = value
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.ok_or_else(|| format!("expected a quoted string, found `{value}`"))?;
if inner.contains('"') || inner.contains('\\') {
return Err("quotes and escapes inside strings are unsupported in lucisv.toml".to_string());
}
Ok(inner.to_string())
}
/// Drops a trailing `# comment` from a value. A `#` inside a string is
/// literal, so quoting is tracked (strings have no escapes here).
fn strip_comment(value: &str) -> &str {
let mut in_string = false;
for (i, c) in value.char_indices() {
match c {
'"' => in_string = !in_string,
'#' if !in_string => return value[..i].trim_end(),
_ => {}
}
}
value
}
/// Finds the config file governing each input, caching the answer per
/// directory so a whole tree under one config file parses it once.
pub struct Discovery {
enabled: bool,
cwd: PathBuf,
cache: HashMap<PathBuf, FileConfig>,
}
impl Discovery {
/// A discovery that searches upward, or — when `enabled` is false
/// (`--no-config`) — one that always answers "no config".
pub fn new(enabled: bool) -> Discovery {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
Discovery { enabled, cwd, cache: HashMap::new() }
}
/// The config governing a path named on the command line: the path
/// itself when it is a directory, otherwise its parent directory.
pub fn for_input(&mut self, path: &Path) -> Result<FileConfig, String> {
if path.is_dir() {
self.for_dir(path)
} else {
self.for_file(path)
}
}
/// The config governing `path`, searched from the directory holding it.
pub fn for_file(&mut self, path: &Path) -> Result<FileConfig, String> {
if !self.enabled {
return Ok(FileConfig::default());
}
let absolute = self.absolute(path);
match absolute.parent() {
Some(dir) => self.for_dir(dir),
None => Ok(FileConfig::default()),
}
}
/// The config governing directory `dir` itself.
pub fn for_dir(&mut self, dir: &Path) -> Result<FileConfig, String> {
if !self.enabled {
return Ok(FileConfig::default());
}
let start = self.absolute(dir);
let mut cursor = start.as_path();
// Directories that resolve to the same answer as `cursor` does.
let mut chain: Vec<PathBuf> = Vec::new();
let found = loop {
if let Some(hit) = self.cache.get(cursor) {
break hit.clone();
}
chain.push(cursor.to_path_buf());
if let Some(file) = config_file_in(cursor) {
break load(&file)?;
}
// The `.git` stop happens after this directory was checked, so
// a config file next to `.git` in a repo root is still found.
if cursor.join(".git").exists() {
break FileConfig::default();
}
match cursor.parent() {
Some(parent) => cursor = parent,
None => break FileConfig::default(),
}
};
for dir in chain {
self.cache.insert(dir, found.clone());
}
Ok(found)
}
/// Resolves `path` against the current directory and folds away `.`
/// and `..` so the upward walk visits real ancestors. Symlinks are
/// deliberately not resolved.
fn absolute(&self, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { self.cwd.join(path) };
let mut out = PathBuf::new();
for component in joined.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
}
fn config_file_in(dir: &Path) -> Option<PathBuf> {
NAMES.iter().map(|name| dir.join(name)).find(|path| path.is_file())
}
fn load(path: &Path) -> Result<FileConfig, String> {
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
let mut config = parse(&text).map_err(|e| format!("{}:{e}", path.display()))?;
// `filelist` is the one value that names another file, so it is resolved
// here — against the config file's own directory, which `parse` cannot
// know. An absolute path is left alone (`join` already does that).
let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
if let Some(filelist) = config.filelist.take() {
config.filelist = Some(dir.join(filelist));
}
// `[lint] waivers` names other files the same way, and is resolved the
// same way: against the config file's directory, an absolute path left
// alone by `join`.
if let Some(waivers) = config.lint_waivers.take() {
config.lint_waivers = Some(waivers.into_iter().map(|file| dir.join(file)).collect());
}
// So an error about a `[lint.<rule>]` entry can name the file to edit.
config.source = Some(path.to_path_buf());
Ok(config)
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
fn ok(text: &str) -> FileConfig {
parse(text).expect("parse")
}
fn err(text: &str) -> String {
parse(text).expect_err("expected a parse error")
}
#[test]
fn parses_every_supported_form() {
let config = ok("\
# a comment
line-length = 80
indent=4 # trailing comment
exclude = [ \"build\", \"*_gen.sv\", ]
");
assert_eq!(config.line_length, Some(80));
assert_eq!(config.indent, Some(4));
assert_eq!(config.exclude, Some(vec!["build".to_string(), "*_gen.sv".to_string()]));
}
#[test]
fn the_filelist_key_is_a_string_and_nothing_else() {
assert_eq!(ok("filelist = \"rtl/files.f\"").filelist, Some(PathBuf::from("rtl/files.f")));
assert!(err("filelist = 3").contains("expected a quoted string"));
assert!(err("filelist = [\"a.f\"]").contains("expected a quoted string"));
assert!(err("filelist = \"a.f\"\nfilelist = \"b.f\"").contains("duplicate key `filelist`"));
// The key is named in the unknown-key message, so a typo says what
// was available.
assert!(err("file-list = \"a.f\"").contains("filelist"));
}
#[test]
fn a_relative_filelist_resolves_against_the_config_files_directory() {
let tree = TempTree::new();
tree.write("lucisv.toml", "filelist = \"rtl/files.f\"\n");
let deep = tree.write("a/b/x.sv", "");
let mut discovery = Discovery::new(true);
let found = discovery.for_file(&deep).unwrap();
assert_eq!(found.filelist, Some(tree.path.join("rtl/files.f")));
}
#[test]
fn an_absolute_filelist_is_left_alone() {
let tree = TempTree::new();
tree.write("lucisv.toml", "filelist = \"/opt/project/files.f\"\n");
let file = tree.write("x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(
discovery.for_file(&file).unwrap().filelist,
Some(PathBuf::from("/opt/project/files.f"))
);
}
/// `[lint] waivers` names other files, so it resolves the way `filelist`
/// does: against the config file's own directory, absolute paths left
/// alone. See `docs/features/waiver-files/README.md`.
#[test]
fn lint_waivers_are_a_list_resolved_against_the_config_files_directory() {
assert_eq!(
ok("[lint]\nwaivers = [ \"a.waiver\", \"deep/b.waiver\" ]").lint_waivers,
Some(vec![PathBuf::from("a.waiver"), PathBuf::from("deep/b.waiver")])
);
assert_eq!(
ok("[lint]\nselect = [\"no-tabs\"]").lint_waivers,
None,
"absent unless written"
);
assert!(err("[lint]\nwaivers = \"a.waiver\"").contains("multi-line arrays"));
assert!(err("[lint]\nwaivers = []\nwaivers = []").contains("duplicate key `waivers`"));
assert!(err("[lint]\nwaiver = []").contains("unknown key `waiver` under `[lint]`"));
let tree = TempTree::new();
tree.write("lucisv.toml", "[lint]\nwaivers = [ \"rtl/a.waiver\", \"/opt/b.waiver\" ]\n");
let deep = tree.write("a/b/x.sv", "");
let found = Discovery::new(true).for_file(&deep).unwrap();
assert_eq!(
found.lint_waivers,
Some(vec![tree.path.join("rtl/a.waiver"), PathBuf::from("/opt/b.waiver")])
);
}
#[test]
fn an_empty_file_sets_nothing() {
assert_eq!(ok(""), FileConfig::default());
assert_eq!(ok("# just a comment\n\n"), FileConfig::default());
assert_eq!(ok("exclude = []").exclude, Some(Vec::new()));
}
#[test]
fn a_hash_inside_a_string_is_not_a_comment() {
assert_eq!(ok("exclude = [\"a#b\"]").exclude, Some(vec!["a#b".to_string()]));
}
#[test]
fn a_leading_bom_is_stripped() {
assert_eq!(ok("\u{feff}indent = 4").indent, Some(4));
}
#[test]
fn a_signed_integer_is_rejected() {
// The documented grammar is `digit+`; `+4` is from_str-parseable
// but outside it.
assert!(err("indent = +4").contains("expects an integer"));
}
#[test]
fn unknown_keys_are_rejected_by_name() {
let message = err("line_length = 80");
assert!(message.contains("unknown key `line_length`"), "{message}");
assert!(message.starts_with("1: "), "{message}");
// The line number counts blank and comment lines.
assert!(err("# c\n\nbogus = 1").starts_with("3: "));
}
#[test]
fn out_of_range_values_are_rejected() {
assert!(err("line-length = 39").contains("between 40 and 400"));
assert!(err("line-length = 401").contains("between 40 and 400"));
assert!(err("indent = 0").contains("between 1 and 8"));
assert!(err("indent = 9").contains("between 1 and 8"));
assert_eq!(ok("line-length = 40\nindent = 8").line_length, Some(40));
}
#[test]
fn bad_values_are_rejected() {
assert!(err("line-length = wide").contains("expects an integer"));
assert!(err("line-length = \"80\"").contains("expects an integer"));
assert!(err("line-length = 8.0").contains("expects an integer"));
assert!(err("indent =").contains("has no value"));
assert!(err("exclude = \"build\"").contains("multi-line arrays are unsupported"));
assert!(err("exclude = [build]").contains("expected a quoted string"));
assert!(err("exclude = [\"a\", ,]").contains("expected a quoted string"));
}
#[test]
fn unsupported_toml_is_named_not_ignored() {
assert!(err("[tool.lucisv]\nindent = 2").contains("unknown table"));
assert!(err("exclude = [\n \"a\",\n]").contains("multi-line arrays are unsupported"));
assert!(err("exclude = [\"a\\tb\"]").contains("escapes"));
assert!(err("indent").contains("expected `key = value`"));
}
#[test]
fn duplicate_keys_are_rejected() {
assert!(err("indent = 2\nindent = 4").contains("duplicate key `indent`"));
assert!(err("exclude = []\nexclude = []").contains("duplicate key `exclude`"));
assert!(
err("[lint]\nignore = [\"a\"]\nignore = [\"b\"]").contains("duplicate key `ignore`")
);
}
/// The `[format]` table: the layout keys that change how an already-clean
/// file is laid out, and so are off unless a checked-in `lucisv.toml`
/// turns them on (TODO §54.3).
#[test]
fn the_format_table_carries_uvm_utils_indent() {
assert_eq!(ok("[format]\nuvm-utils-indent = true").format_uvm_utils_indent, Some(true));
assert_eq!(ok("[format]\nuvm-utils-indent = false").format_uvm_utils_indent, Some(false));
// Absent unless written — which is what makes the default off.
assert_eq!(ok("indent = 4").format_uvm_utils_indent, None);
assert_eq!(ok("[format]").format_uvm_utils_indent, None);
// The formatter keys still work above the table, and nothing closes
// the table but the next header.
let mixed = parse(
"indent = 4\n\n[format]\nuvm-utils-indent = true\n\n[lint]\nignore = [\"no-tabs\"]",
)
.expect("parses");
assert_eq!(mixed.indent, Some(4));
assert_eq!(mixed.format_uvm_utils_indent, Some(true));
assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
}
/// Everything about the table's shape, the way the `[lint]` table's is
/// pinned: an unknown key is named, a non-boolean value is refused, and a
/// repeated key is an error rather than a last-one-wins.
#[test]
fn the_format_table_rejects_what_it_does_not_support() {
assert!(err("[format]\nbogus = true").contains("unknown key `bogus` under `[format]`"));
assert!(err("[format]\nuvm-utils-indent = \"yes\"")
.contains("`uvm-utils-indent` expects `true` or `false`, found `\"yes\"`"));
assert!(err("[format]\nuvm-utils-indent = 1").contains("expects `true` or `false`"));
assert!(err("[format]\nuvm-utils-indent =").contains("has no value"));
assert!(err("[format]\nuvm-utils-indent = true\nuvm-utils-indent = false")
.contains("duplicate key `uvm-utils-indent`"));
// A key before any table still belongs to the top level, and the
// top-level unknown-key message names the table it does belong to.
assert!(err("uvm-utils-indent = true").contains("unknown key `uvm-utils-indent`"));
assert!(err("uvm-utils-indent = true").contains("`[format]`"));
// `[format.<anything>]` is not a table this parser knows.
assert!(err("[format.uvm]\nx = 1").contains("unknown table"));
}
/// The same key in a real config file, so the message a user sees names
/// the file and the line to edit — the ladder `[format]` sits at the top
/// of (`lucisv.toml` outranks the editor setting).
#[test]
fn a_bad_format_key_names_the_file_and_line() {
let tree = TempTree::new();
let config = tree.write("lucisv.toml", "indent = 2\n\n[format]\nuvm-utils-indnet = true\n");
let file = tree.write("x.sv", "");
let message = Discovery::new(true).for_file(&file).expect_err("expected an error");
assert!(message.starts_with(&format!("{}:4: ", config.display())), "{message}");
assert!(message.contains("unknown key `uvm-utils-indnet` under `[format]`"), "{message}");
// And the key spelled right loads through the same walk.
let good = TempTree::new();
good.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n");
let sv = good.write("a/b/x.sv", "");
assert_eq!(Discovery::new(true).for_file(&sv).unwrap().format_uvm_utils_indent, Some(true));
}
/// The `[lint]` table: the off switch a round that turns rules on by
/// default owes its users (topo §2.9-4).
#[test]
fn the_lint_table_carries_select_and_ignore() {
let config =
parse("[lint]\nselect = [\"no-tabs\", \"unused-signal\"]\nignore = [\"no-tabs\"]")
.expect("parses");
assert_eq!(
config.lint_select.as_deref(),
Some(&["no-tabs".to_string(), "unused-signal".to_string()][..])
);
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
// Both are absent unless written, and the formatter keys still work
// above the table.
let mixed = parse("indent = 4\n\n[lint]\nignore = [\"unused-signal\"]").expect("parses");
assert_eq!(mixed.indent, Some(4));
assert_eq!(mixed.lint_select, None);
assert_eq!(parse("indent = 4").expect("parses").lint_ignore, None);
}
/// Rule *names* are not this crate's business — it has no registry to
/// check them against — but everything about the table's shape is.
#[test]
fn the_lint_table_rejects_what_it_does_not_support() {
assert!(err("[lint]\nbogus = [\"a\"]").contains("unknown key `bogus` under `[lint]`"));
assert!(err("[lint]\nselect = \"no-tabs\"").contains("multi-line arrays are unsupported"));
assert!(err("[lint.]\nx = 1").contains("not a rule table"));
assert!(err("[lint.a.b]\nx = 1").contains("not a rule table"));
assert!(err("[lint]\nindent = 4").contains("unknown key `indent` under `[lint]`"));
// A key before any table still belongs to the top level.
assert!(err("select = [\"no-tabs\"]").contains("unknown key `select`"));
// Nothing closes the table — TOML's own rule, spelled out.
assert_eq!(
parse("[lint]\nselect = [\"no-tabs\"]").expect("parses").lint_select.as_deref(),
Some(&["no-tabs".to_string()][..])
);
}
/// The per-rule tables: stored exactly as written, because this crate
/// has no idea what a rule is or what its options take.
#[test]
fn a_rule_table_keeps_its_entries_as_written() {
let config = parse(
"[lint]\nignore = [\"no-tabs\"]\n\n\
[lint.line-length]\nlength = 120\n\n\
[lint.signal-name-style]\nstyle_regex = \"[a-z_0-9]+\" # ours\n",
)
.expect("parses");
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
let entries: Vec<(&str, &str, &str, usize)> = config
.lint_options
.iter()
.map(|o| (o.rule.as_str(), o.key.as_str(), o.raw.as_str(), o.line))
.collect();
assert_eq!(
entries,
vec![
("line-length", "length", "120", 5),
("signal-name-style", "style_regex", "\"[a-z_0-9]+\"", 8),
]
);
}
/// A backslash is legal in an option value and refused in a top-level
/// string: the linter's own parser reads the former, and a pattern is the
/// one value that needs them.
#[test]
fn a_rule_option_value_is_not_string_checked_here() {
let config =
parse("[lint.signal-name-style]\nstyle_regex = \"[a-z]\\d+\"\n").expect("parses");
assert_eq!(config.lint_options[0].raw, "\"[a-z]\\d+\"");
assert!(err("exclude = [\"a\\d\"]").contains("escapes"), "still refused up here");
}
#[test]
fn a_rule_table_rejects_a_repeated_key_and_a_bad_header() {
assert!(err("[lint.line-length]\nlength = 1\nlength = 2")
.contains("duplicate key `length` under `[lint.line-length]`"));
// The same key under two different rules is two different options.
let config = parse(
"[lint.enum-name-style]\nstyle_regex = \"a\"\n\
[lint.module-name-style]\nstyle_regex = \"b\"\n",
)
.expect("parses");
assert_eq!(config.lint_options.len(), 2);
assert!(err("[lint.a b]\nx = 1").contains("not a rule table"));
}
/// Nothing closes a table: the keys after a rule header belong to it
/// until the next header, and a formatter key written there is that
/// rule's option as far as this parser is concerned.
#[test]
fn a_rule_table_runs_until_the_next_header() {
let config =
parse("indent = 4\n[lint.line-length]\nlength = 120\nindent = 8\n").expect("parses");
assert_eq!(config.indent, Some(4));
assert_eq!(config.lint_options.len(), 2);
assert_eq!(config.lint_options[1].key, "indent");
}
#[test]
fn a_config_file_records_where_it_came_from() {
let tree = TempTree::new();
let written = tree.write("lucisv.toml", "[lint.line-length]\nlength = 120\n");
let file = tree.write("x.sv", "");
let found = Discovery::new(true).for_file(&file).expect("reads");
assert_eq!(found.source.as_deref(), Some(written.as_path()));
// `parse` alone has no path to record.
assert_eq!(parse("indent = 4").expect("parses").source, None);
}
/// A throwaway directory tree under the system temp dir.
struct TempTree {
path: PathBuf,
}
impl TempTree {
fn new() -> TempTree {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("lucisv-config-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
TempTree { path }
}
fn write(&self, rel: &str, contents: &str) -> PathBuf {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::fs::write(&path, contents).expect("write");
path
}
fn dir(&self, rel: &str) -> PathBuf {
let path = self.path.join(rel);
std::fs::create_dir_all(&path).expect("create dir");
path
}
}
impl Drop for TempTree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[test]
fn searches_upward_from_the_files_directory() {
let tree = TempTree::new();
tree.write("lucisv.toml", "indent = 4\n");
let deep = tree.write("a/b/c/x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(discovery.for_file(&deep).unwrap().indent, Some(4));
}
#[test]
fn the_nearest_config_wins_and_does_not_merge() {
let tree = TempTree::new();
tree.write("lucisv.toml", "indent = 4\nline-length = 120\n");
tree.write("a/lucisv.toml", "indent = 8\n");
let near = tree.write("a/x.sv", "");
let far = tree.write("b/x.sv", "");
let mut discovery = Discovery::new(true);
let near = discovery.for_file(&near).unwrap();
assert_eq!(near.indent, Some(8));
assert_eq!(near.line_length, None, "a nearer config replaces, never merges");
let far = discovery.for_file(&far).unwrap();
assert_eq!((far.indent, far.line_length), (Some(4), Some(120)));
}
#[test]
fn dotted_name_is_the_fallback_in_one_directory() {
let tree = TempTree::new();
tree.write(".lucisv.toml", "indent = 3\n");
let only_dotted = tree.write("x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(discovery.for_file(&only_dotted).unwrap().indent, Some(3));
tree.write("lucisv.toml", "indent = 5\n");
let mut discovery = Discovery::new(true);
assert_eq!(
discovery.for_file(&only_dotted).unwrap().indent,
Some(5),
"lucisv.toml is preferred when both are present"
);
}
#[test]
fn git_stops_the_walk_but_only_after_its_own_directory() {
let tree = TempTree::new();
tree.write("lucisv.toml", "indent = 4\n");
tree.dir("repo/.git");
tree.write("repo/lucisv.toml", "indent = 8\n");
let inside = tree.write("repo/rtl/x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(
discovery.for_file(&inside).unwrap().indent,
Some(8),
"the repo root's own config is checked before `.git` stops the walk"
);
// With no config in the repo root, the walk stops there rather
// than escaping into the parent's config.
let tree = TempTree::new();
tree.write("lucisv.toml", "indent = 4\n");
tree.dir("repo/.git");
let inside = tree.write("repo/rtl/x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(discovery.for_file(&inside).unwrap(), FileConfig::default());
}
#[test]
fn a_git_file_stops_the_walk_too() {
// Submodules and worktrees have a `.git` *file*, not a directory.
let tree = TempTree::new();
tree.write("lucisv.toml", "indent = 4\n");
tree.write("repo/.git", "gitdir: ../.git/modules/repo\n");
let inside = tree.write("repo/x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(discovery.for_file(&inside).unwrap(), FileConfig::default());
}
#[test]
fn disabled_discovery_reads_nothing() {
let tree = TempTree::new();
tree.write("lucisv.toml", "this is not even valid\n");
let file = tree.write("x.sv", "");
let mut discovery = Discovery::new(false);
assert_eq!(discovery.for_file(&file).unwrap(), FileConfig::default());
}
#[test]
fn a_broken_config_is_an_error_naming_file_and_line() {
let tree = TempTree::new();
let config = tree.write("lucisv.toml", "indent = 2\nbogus = 1\n");
let file = tree.write("x.sv", "");
let message = Discovery::new(true).for_file(&file).expect_err("expected an error");
assert!(message.starts_with(&format!("{}:2: ", config.display())), "{message}");
assert!(message.contains("unknown key `bogus`"), "{message}");
}
#[test]
fn the_cache_answers_for_every_directory_on_the_walked_chain() {
let tree = TempTree::new();
tree.write("lucisv.toml", "indent = 4\n");
let deep = tree.write("a/b/c/x.sv", "");
let mut discovery = Discovery::new(true);
assert_eq!(discovery.for_file(&deep).unwrap().indent, Some(4));
assert!(discovery.cache.contains_key(&tree.path.join("a/b/c")));
assert!(discovery.cache.contains_key(&tree.path.join("a")));
assert!(discovery.cache.contains_key(&tree.path));
// Deleting the file afterwards proves the second lookup is served
// from the cache and not from disk.
std::fs::remove_file(tree.path.join("lucisv.toml")).expect("remove config");
assert_eq!(discovery.for_file(&tree.path.join("a/b/y.sv")).unwrap().indent, Some(4));
}
#[test]
fn a_directory_input_resolves_from_itself() {
let tree = TempTree::new();
tree.write("a/lucisv.toml", "indent = 8\n");
tree.write("lucisv.toml", "indent = 4\n");
let dir = tree.dir("a");
let mut discovery = Discovery::new(true);
assert_eq!(discovery.for_input(&dir).unwrap().indent, Some(8));
}
#[test]
fn relative_and_dotted_paths_resolve_against_the_cwd() {
let tree = TempTree::new();
let mut discovery = Discovery::new(true);
discovery.cwd = tree.path.clone();
tree.write("lucisv.toml", "indent = 4\n");
tree.write("a/b/x.sv", "");
assert_eq!(discovery.for_file(Path::new("./a/b/x.sv")).unwrap().indent, Some(4));
assert_eq!(discovery.for_file(Path::new("a/b/../b/x.sv")).unwrap().indent, Some(4));
// A file with no directory part at all searches the cwd.
tree.write("y.sv", "");
assert_eq!(discovery.for_file(Path::new("y.sv")).unwrap().indent, Some(4));
}
}