editor-packaging: a minimal VS Code extension (41-line plain JS on
vscode-languageclient =9.0.1, one setting vfmt.serverPath, languages
verilog/systemverilog) with a zero-dependency smoke.js that validates
the extension's exact spawn contract against the real binary, plus
Neovim/Vim/coc setup docs (including the load-bearing
vim.filetype.add — Vim maps *.v by content heuristic and *.vh not at
all). Everything headless-validatable was validated: the .vsix
builds, smoke passes with negative controls, npm ci reproduces.
vfmt-core-lift: config.rs and walk.rs moved to a new std-only
vfmt_core crate as byte-identical 100% renames (CLI suite untouched,
corpus TSV md5 equal from HEAD and lifted builds). The LSP server
now discovers vfmt.toml per document with precedence config > client
tabSize > built-in default (an editor default is not a deliberate
override), warns once per document change on a broken config while
formatting with defaults, and scans the workspace with the lifted
gitignore-aware walk. QA drove every claim live over stdio.
With these, every TODO §6 item is delivered: spans, tolerant
parsing, define table, single-file semantics, workspace index, the
server, and both editors. Lead trued up the caveats this round made
stale across five documents.
Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{editor-packaging,vfmt-core-lift}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
407 lines
16 KiB
Rust
407 lines
16 KiB
Rust
//! Hand-rolled command line parsing for the `vfmt` binary.
|
|
|
|
use vfmt_core::config::FileConfig;
|
|
use vlog_formatter::Config;
|
|
|
|
/// Which tool this invocation runs.
|
|
///
|
|
/// A bare `vfmt <paths>` is [`Command::Format`], exactly as before
|
|
/// subcommands existed; the word is only read when it is the **first**
|
|
/// argument, so `vfmt --check rtl/` and every other old command line means
|
|
/// what it always did.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Command {
|
|
/// `vfmt`, `vfmt format` — the formatter.
|
|
Format,
|
|
/// `vfmt check` — the linter.
|
|
Check,
|
|
}
|
|
|
|
/// How `vfmt check` renders its diagnostics.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum OutputFormat {
|
|
/// `FILE:LINE:COL: message [rule-name]`, one per line.
|
|
Text,
|
|
/// One JSON array of diagnostic objects.
|
|
Json,
|
|
}
|
|
|
|
/// Everything the driver needs to know about one invocation.
|
|
pub struct Options {
|
|
/// Formatter or linter.
|
|
pub command: Command,
|
|
/// Don't write; report files that would be reformatted.
|
|
pub check: bool,
|
|
/// Don't write; print a unified diff of what would change.
|
|
pub diff: bool,
|
|
/// Print formatted output instead of rewriting files.
|
|
pub stdout: bool,
|
|
/// Ignore `vfmt.toml` / `.vfmt.toml` files entirely.
|
|
pub no_config: bool,
|
|
/// Ignore `.gitignore` files while walking directories.
|
|
pub no_gitignore: bool,
|
|
/// `--threads`: worker count for the file pool. `None` or `Some(0)`
|
|
/// means rayon's default, one per logical CPU.
|
|
pub threads: Option<usize>,
|
|
/// Path to report instead of `<stdin>` when input comes from stdin.
|
|
/// Also the directory config discovery anchors on.
|
|
pub stdin_filename: Option<String>,
|
|
/// Patterns skipped while walking directories.
|
|
pub exclude: Vec<String>,
|
|
/// `--line-length`, if given; otherwise the config file decides.
|
|
pub line_length: Option<usize>,
|
|
/// `--indent`, if given; otherwise the config file decides.
|
|
pub indent: Option<usize>,
|
|
/// `check` only: how diagnostics are rendered.
|
|
pub output_format: OutputFormat,
|
|
/// `check` only: apply safe fixes and write the files back.
|
|
pub fix: bool,
|
|
/// `check` only: let `--fix` apply unsafe fixes too.
|
|
pub unsafe_fixes: bool,
|
|
/// `check` only: run exactly these rules (empty means the default set).
|
|
pub select: Vec<String>,
|
|
/// `check` only: rules to drop from whatever `--select` left.
|
|
pub ignore: Vec<String>,
|
|
/// Files, directories, or the single input `-`.
|
|
pub inputs: Vec<String>,
|
|
}
|
|
|
|
impl Options {
|
|
/// True when this run must not modify any file.
|
|
pub fn read_only(&self) -> bool {
|
|
self.check || self.diff
|
|
}
|
|
|
|
/// True when the single input is `-`, i.e. the buffer comes from stdin.
|
|
pub fn is_stdin(&self) -> bool {
|
|
self.inputs.len() == 1 && self.inputs[0] == "-"
|
|
}
|
|
|
|
/// Formatter settings for one file: CLI flag > config file > default.
|
|
pub fn config_with(&self, file: &FileConfig) -> Config {
|
|
let mut config = Config::default();
|
|
if let Some(n) = self.line_length.or(file.line_length) {
|
|
config.max_width = n;
|
|
}
|
|
if let Some(n) = self.indent.or(file.indent) {
|
|
config.indent_width = n;
|
|
}
|
|
config
|
|
}
|
|
|
|
/// The `--exclude` patterns for one walk: CLI patterns plus whatever
|
|
/// the config file governing that input adds.
|
|
pub fn exclude_with(&self, file: &FileConfig) -> Vec<String> {
|
|
let mut exclude = self.exclude.clone();
|
|
exclude.extend(file.exclude.iter().flatten().cloned());
|
|
exclude
|
|
}
|
|
|
|
/// Worker threads to build the pool with; 0 lets rayon decide.
|
|
pub fn thread_count(&self) -> usize {
|
|
self.threads.unwrap_or(0)
|
|
}
|
|
}
|
|
|
|
/// Prints the `--help` text, including the frozen exit-code contract.
|
|
pub fn print_help() {
|
|
println!(
|
|
"vfmt — a Verilog/SystemVerilog formatter and linter
|
|
|
|
USAGE:
|
|
vfmt [OPTIONS] <file|dir>... format files in place
|
|
vfmt format [OPTIONS] <file|dir>... the same, spelled out
|
|
vfmt check [OPTIONS] <file|dir>... lint files
|
|
vfmt - read from stdin, write to stdout
|
|
|
|
A subcommand is only recognized as the *first* argument, so every command
|
|
line that worked before subcommands existed still formats. To format a
|
|
file actually named `check`, write `vfmt format check` or `./check`.
|
|
|
|
OPTIONS:
|
|
--check don't write; exit 1 if any file would be reformatted
|
|
--diff don't write; print a unified diff of what would change
|
|
--stdout print formatted output instead of rewriting files
|
|
--exclude <PATTERN> skip matching paths when walking directories; may be
|
|
repeated. A pattern with `/` matches a path suffix,
|
|
otherwise it matches a file or directory name; `*`
|
|
matches within one path component
|
|
--stdin-filename <PATH> path to report in messages for input read from stdin;
|
|
also the directory config discovery starts from
|
|
--no-gitignore don't read .gitignore files while walking directories
|
|
--threads <N> worker threads used to format files (default: one per
|
|
logical CPU). `--threads 1` formats on a single worker;
|
|
the output and exit code are identical either way
|
|
--line-length <N> maximum line length (default 100)
|
|
--indent <N> indent width in spaces (default 2)
|
|
--no-config ignore vfmt.toml / .vfmt.toml files
|
|
-h, --help show this help
|
|
-V, --version show version
|
|
|
|
CHECK OPTIONS (`vfmt check` only):
|
|
--select <RULES> run only these rules (comma-separated, repeatable)
|
|
--ignore <RULES> drop these rules from the set that would run
|
|
--output-format <FMT> `text` (default): FILE:LINE:COL: message [rule];
|
|
`json`: one array of diagnostic objects
|
|
--fix apply safe fixes and write the files back
|
|
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
|
|
one yet, so today this changes nothing)
|
|
|
|
Suppress a finding with a comment: `// vfmt: waive <rule>` on the line
|
|
itself or on the line above it, or a `// vfmt: waive-start <rule>` /
|
|
`// vfmt: waive-stop <rule>` pair around a region. `verilog_lint:` is
|
|
accepted in place of `vfmt:`. A waiver that suppresses nothing is
|
|
reported under the `unused-waiver` rule.
|
|
|
|
IGNORE FILES:
|
|
While walking a directory, vfmt reads a `.gitignore` in every directory it
|
|
enters and skips what it names; a deeper file overrides a shallower one and
|
|
the last matching line wins. Supported: `#` comments, `*` inside one path
|
|
component, a leading or embedded `/` (anchors to that .gitignore's own
|
|
directory), a trailing `/` (directories only) and `!` negation. Not
|
|
supported: `**`, `?`, character classes, `\\` escapes and the global/repo
|
|
excludes files. Paths named on the command line are never ignored.
|
|
|
|
CONFIGURATION:
|
|
For each input, vfmt searches upward from its directory for `vfmt.toml`
|
|
or `.vfmt.toml` (the first found wins; the search also stops at a
|
|
directory containing `.git`, after checking it). Recognized keys, all
|
|
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
|
|
patterns, added to `--exclude`). A command line flag overrides the file.
|
|
|
|
EXIT CODES:
|
|
0 nothing to do: files were formatted, --check/--diff found no change,
|
|
or `check` found no violations (or fixed all of them)
|
|
1 --check/--diff only: at least one file would be reformatted;
|
|
`check`: at least one violation was reported
|
|
2 an error occurred (bad arguments, I/O, a file that could not be
|
|
formatted); files involved in an error are left untouched"
|
|
);
|
|
}
|
|
|
|
/// Parses `std::env::args()`. Exits the process directly for `--help`
|
|
/// and `--version`, which have no useful `Options` to return.
|
|
pub fn parse() -> Result<Options, String> {
|
|
parse_from(std::env::args().skip(1))
|
|
}
|
|
|
|
fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
|
let mut opts = Options {
|
|
command: Command::Format,
|
|
check: false,
|
|
diff: false,
|
|
stdout: false,
|
|
no_config: false,
|
|
no_gitignore: false,
|
|
threads: None,
|
|
stdin_filename: None,
|
|
exclude: Vec::new(),
|
|
line_length: None,
|
|
indent: None,
|
|
output_format: OutputFormat::Text,
|
|
fix: false,
|
|
unsafe_fixes: false,
|
|
select: Vec::new(),
|
|
ignore: Vec::new(),
|
|
inputs: Vec::new(),
|
|
};
|
|
let mut args = args.peekable();
|
|
// The subcommand, if there is one, is the very first argument — so every
|
|
// command line that worked before subcommands existed still formats.
|
|
match args.peek().map(String::as_str) {
|
|
Some("check") => {
|
|
opts.command = Command::Check;
|
|
args.next();
|
|
}
|
|
Some("format") => {
|
|
args.next();
|
|
}
|
|
_ => {}
|
|
}
|
|
while let Some(arg) = args.next() {
|
|
match arg.as_str() {
|
|
"--check" => opts.check = true,
|
|
"--diff" => opts.diff = true,
|
|
"--stdout" => opts.stdout = true,
|
|
"--no-config" => opts.no_config = true,
|
|
"--no-gitignore" => opts.no_gitignore = true,
|
|
"--threads" => {
|
|
let v = args.next().ok_or("--threads requires a value")?;
|
|
opts.threads = Some(v.parse().map_err(|_| format!("invalid thread count: {v}"))?);
|
|
}
|
|
"--exclude" => {
|
|
let v = args.next().ok_or("--exclude requires a value")?;
|
|
opts.exclude.push(v);
|
|
}
|
|
"--stdin-filename" => {
|
|
let v = args.next().ok_or("--stdin-filename requires a value")?;
|
|
opts.stdin_filename = Some(v);
|
|
}
|
|
"--line-length" => {
|
|
let v = args.next().ok_or("--line-length requires a value")?;
|
|
opts.line_length =
|
|
Some(v.parse().map_err(|_| format!("invalid line length: {v}"))?);
|
|
}
|
|
"--indent" => {
|
|
let v = args.next().ok_or("--indent requires a value")?;
|
|
opts.indent = Some(v.parse().map_err(|_| format!("invalid indent: {v}"))?);
|
|
}
|
|
"--output-format" => {
|
|
let v = args.next().ok_or("--output-format requires a value")?;
|
|
opts.output_format = match v.as_str() {
|
|
"text" => OutputFormat::Text,
|
|
"json" => OutputFormat::Json,
|
|
other => return Err(format!("unknown output format: {other} (text, json)")),
|
|
};
|
|
}
|
|
"--fix" => opts.fix = true,
|
|
"--unsafe-fixes" => opts.unsafe_fixes = true,
|
|
"--select" => {
|
|
let v = args.next().ok_or("--select requires a value")?;
|
|
opts.select.extend(split_rules(&v));
|
|
}
|
|
"--ignore" => {
|
|
let v = args.next().ok_or("--ignore requires a value")?;
|
|
opts.ignore.extend(split_rules(&v));
|
|
}
|
|
"-h" | "--help" => {
|
|
print_help();
|
|
std::process::exit(0);
|
|
}
|
|
"-V" | "--version" => {
|
|
println!("vfmt {}", env!("CARGO_PKG_VERSION"));
|
|
std::process::exit(0);
|
|
}
|
|
"-" => opts.inputs.push("-".to_string()),
|
|
s if s.starts_with('-') => return Err(format!("unknown option: {s}")),
|
|
s => opts.inputs.push(s.to_string()),
|
|
}
|
|
}
|
|
if opts.inputs.is_empty() {
|
|
return Err("no input files (try `vfmt --help`)".to_string());
|
|
}
|
|
if opts.diff && opts.stdout {
|
|
return Err("--diff cannot be combined with --stdout".to_string());
|
|
}
|
|
check_flag_scopes(&opts)?;
|
|
Ok(opts)
|
|
}
|
|
|
|
/// A comma-separated rule list, `--select no-tabs,module-filename`. Repeating
|
|
/// the flag works too and the lists are concatenated.
|
|
fn split_rules(value: &str) -> Vec<String> {
|
|
value.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).collect()
|
|
}
|
|
|
|
/// Rejects a flag used with the wrong subcommand. A quiet no-op would be the
|
|
/// worse outcome: `vfmt check --diff` looking like it worked, having linted
|
|
/// nothing.
|
|
fn check_flag_scopes(opts: &Options) -> Result<(), String> {
|
|
let lint_only = [
|
|
(opts.fix, "--fix"),
|
|
(opts.unsafe_fixes, "--unsafe-fixes"),
|
|
(opts.output_format != OutputFormat::Text, "--output-format"),
|
|
(!opts.select.is_empty(), "--select"),
|
|
(!opts.ignore.is_empty(), "--ignore"),
|
|
];
|
|
let format_only = [(opts.check, "--check"), (opts.diff, "--diff"), (opts.stdout, "--stdout")];
|
|
match opts.command {
|
|
Command::Format => {
|
|
for (given, flag) in lint_only {
|
|
if given {
|
|
return Err(format!("{flag} is only valid for `vfmt check`"));
|
|
}
|
|
}
|
|
}
|
|
Command::Check => {
|
|
for (given, flag) in format_only {
|
|
if given {
|
|
return Err(format!("{flag} is not valid for `vfmt check`"));
|
|
}
|
|
}
|
|
if opts.unsafe_fixes && !opts.fix {
|
|
return Err("--unsafe-fixes requires --fix".to_string());
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn parse(args: &[&str]) -> Result<Options, String> {
|
|
parse_from(args.iter().map(|s| s.to_string()))
|
|
}
|
|
|
|
#[test]
|
|
fn collects_repeated_excludes() {
|
|
let opts = parse(&["--exclude", "build", "--exclude", "*_gen.sv", "rtl"]).unwrap();
|
|
assert_eq!(opts.exclude, vec!["build", "*_gen.sv"]);
|
|
assert_eq!(opts.inputs, vec!["rtl"]);
|
|
}
|
|
|
|
#[test]
|
|
fn diff_and_stdout_conflict() {
|
|
assert!(parse(&["--diff", "--stdout", "rtl"]).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn stdin_filename_is_stored_verbatim() {
|
|
let opts = parse(&["--stdin-filename", "a/b.sv", "-"]).unwrap();
|
|
assert_eq!(opts.stdin_filename.as_deref(), Some("a/b.sv"));
|
|
assert!(!opts.read_only());
|
|
}
|
|
|
|
#[test]
|
|
fn a_cli_flag_beats_the_config_file_which_beats_the_default() {
|
|
let file = FileConfig { line_length: Some(120), indent: Some(4), exclude: None };
|
|
let default = Config::default();
|
|
|
|
let opts = parse(&["rtl"]).unwrap();
|
|
assert_eq!(opts.config_with(&FileConfig::default()).max_width, default.max_width);
|
|
assert_eq!(opts.config_with(&FileConfig::default()).indent_width, default.indent_width);
|
|
assert_eq!(opts.config_with(&file).max_width, 120);
|
|
assert_eq!(opts.config_with(&file).indent_width, 4);
|
|
|
|
// A flag overrides only the setting it names.
|
|
let opts = parse(&["--line-length", "80", "rtl"]).unwrap();
|
|
assert_eq!(opts.config_with(&file).max_width, 80);
|
|
assert_eq!(opts.config_with(&file).indent_width, 4);
|
|
assert_eq!(opts.config_with(&FileConfig::default()).indent_width, default.indent_width);
|
|
}
|
|
|
|
#[test]
|
|
fn config_excludes_are_appended_to_cli_excludes() {
|
|
let file =
|
|
FileConfig { line_length: None, indent: None, exclude: Some(vec!["gen".to_string()]) };
|
|
let opts = parse(&["--exclude", "build", "rtl"]).unwrap();
|
|
assert_eq!(opts.exclude_with(&file), vec!["build", "gen"]);
|
|
assert_eq!(opts.exclude_with(&FileConfig::default()), vec!["build"]);
|
|
}
|
|
|
|
#[test]
|
|
fn missing_value_is_an_error() {
|
|
assert!(parse(&["--exclude"]).is_err());
|
|
assert!(parse(&["--line-length"]).is_err());
|
|
assert!(parse(&["--line-length", "wide", "rtl"]).is_err());
|
|
assert!(parse(&["--threads"]).is_err());
|
|
assert!(parse(&["--threads", "many", "rtl"]).is_err());
|
|
assert!(parse(&["--threads", "-1", "rtl"]).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn thread_count_defaults_to_letting_rayon_decide() {
|
|
assert_eq!(parse(&["rtl"]).unwrap().thread_count(), 0);
|
|
assert_eq!(parse(&["--threads", "0", "rtl"]).unwrap().thread_count(), 0);
|
|
assert_eq!(parse(&["--threads", "4", "rtl"]).unwrap().thread_count(), 4);
|
|
}
|
|
|
|
#[test]
|
|
fn gitignore_is_honored_unless_switched_off() {
|
|
assert!(!parse(&["rtl"]).unwrap().no_gitignore);
|
|
assert!(parse(&["--no-gitignore", "rtl"]).unwrap().no_gitignore);
|
|
}
|
|
}
|