Round 5: CLI path/JSON/stdin and parser/formatter fixes (#1, #11, #42, #44-#47, #55)

This commit is contained in:
Guoliang Chen committed 2026-11-26 14:35:06 -08:00
1 parent 6d1c68994c
commit 4cf50a0b9c
40 files changed
+2767 -430

No files matched your search

+46 -7
View File
@@ -20,12 +20,12 @@ pub enum Command {
Check,
}
/// How `lucisv check` renders its diagnostics.
/// How `lucisv` renders its output when `--output-format` is given.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
/// `FILE:LINE:COL: message [rule-name]`, one per line.
/// Human-readable text (`would reformat: PATH`, `FILE:LINE:COL: message [rule]`).
Text,
/// One JSON array of diagnostic objects.
/// Structured JSON report (format mode) or array of diagnostic objects (`check`).
Json,
}
@@ -65,7 +65,7 @@ pub struct Options {
/// `--lines`: format only the constructs meeting these lines. `None` is a
/// whole-file run.
pub lines: Option<LineRanges>,
/// `check` only: how diagnostics are rendered.
/// How diagnostics (`check`) or format reports (`format`) are rendered.
pub output_format: OutputFormat,
/// `check` only: apply safe fixes and write the files back.
pub fix: bool,
@@ -212,6 +212,11 @@ OPTIONS:
`auto` lays each file out in the preset it is
already closest to, at the default indent/width
--no-config ignore lucisv.toml / .lucisv.toml files
--output-format <FMT> `text` (default): human-readable text output;
`json`: structured JSON report (format mode) or
array of diagnostic objects (`check` mode). In
format mode, cannot be combined with `--diff`,
`--stdout`, or stdin without `--check`
-h, --help show this help
-V, --version show version
@@ -225,8 +230,6 @@ CHECK OPTIONS (`lucisv check` only):
off for a single file or a stdin buffer, where it cannot. `--select` runs
one either way; `--ignore`, or `ignore` under `[lint]` in lucisv.toml,
turns one off.
--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)
@@ -407,6 +410,9 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
}
"--stdin-filename" => {
let v = args.next().ok_or("--stdin-filename requires a value")?;
if v.is_empty() {
return Err("--stdin-filename requires a non-empty path".to_string());
}
opts.stdin_filename = Some(v);
}
"--line-length" => {
@@ -511,7 +517,6 @@ 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"),
(!opts.waiver_files.is_empty(), "--waiver-file"),
@@ -530,6 +535,19 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
return Err(format!("{flag} is only valid for `lucisv check`"));
}
}
if opts.output_format == OutputFormat::Json {
if opts.diff {
return Err("--output-format json cannot be combined with --diff".to_string());
}
if opts.stdout {
return Err("--output-format json cannot be combined with --stdout".to_string());
}
if opts.is_stdin() && !opts.check {
return Err(
"--output-format json requires --check when reading from stdin".to_string()
);
}
}
}
Command::Check => {
for (given, flag) in format_only {
@@ -752,6 +770,27 @@ mod tests {
assert!(parse(&["--rules-doc"]).is_err());
assert!(!parse(&["check", "rtl"]).unwrap().rules_doc);
}
#[test]
fn format_output_format_json_and_stdin_filename_validation() {
assert_eq!(
parse(&["--check", "--output-format", "json", "a.sv"]).unwrap().output_format,
OutputFormat::Json
);
assert_eq!(
parse(&["--output-format", "json", "a.sv"]).unwrap().output_format,
OutputFormat::Json
);
assert_eq!(
parse(&["--check", "--output-format", "json", "-"]).unwrap().output_format,
OutputFormat::Json
);
assert!(parse(&["--diff", "--output-format", "json", "a.sv"]).is_err());
assert!(parse(&["--stdout", "--output-format", "json", "a.sv"]).is_err());
assert!(parse(&["--output-format", "json", "-"]).is_err());
assert!(parse(&["--output-format", "text", "--stdout", "a.sv"]).is_ok());
assert!(parse(&["--stdin-filename", "", "-"]).is_err());
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+2 -2
View File
@@ -344,7 +344,7 @@ fn reads_packages(rule: &'static dyn Rule) -> bool {
}
/// The command line's list when it said anything, else the config file's.
fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
pub(crate) fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
if cli.is_empty() {
config.unwrap_or(&[])
} else {
@@ -714,7 +714,7 @@ fn fix_json(violation: &Violation) -> String {
/// 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.
fn quote(text: &str) -> String {
pub(crate) fn quote(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
+281 -75
View File
@@ -23,18 +23,21 @@ use std::cell::Cell;
use std::collections::HashSet;
use std::io::Read;
use std::panic::AssertUnwindSafe;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use rayon::prelude::*;
use args::{Command, Options};
use args::{Command, Options, OutputFormat};
use lucisv_core::atomic::write_atomic;
use lucisv_core::cache::{content_hash, Cache, Entry};
use lucisv_core::config::{Discovery, FileConfig};
use lucisv_core::filelist;
use lucisv_core::path::normalize_under;
use lucisv_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
use vlog_formatter::{
format_range, format_source, Config, FormatError, LineRanges, VerificationError,
};
use vlog_parser::PARSE_STACK_SIZE;
fn main() -> ExitCode {
@@ -101,46 +104,13 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
if opts.is_stdin() {
let (config, file_config) = match stdin_config(opts) {
Ok(c) => c,
return match run_check_stdin(opts) {
Ok(code) => code,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
ExitCode::from(2)
}
};
let mut src = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut src) {
eprintln!("error: reading stdin: {e}");
return ExitCode::from(2);
}
// A stdin buffer is one text with nothing around it: there is no
// census to build and no other file to ask about, so the rules that
// need a project stay off. `--select` still reaches them.
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
Ok(rules) => rules,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
let options = match lint::rule_options(&file_config) {
Ok(options) => options,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
// A stdin buffer has one config file too — the one governing
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
// reaches it exactly as `[lint] select` does.
let external = match lint::external_waivers(opts, std::iter::once(&file_config)) {
Ok(external) => external,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules, &options, &external);
}
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
Ok(jobs) => jobs,
@@ -158,6 +128,31 @@ fn run_check(opts: &Options) -> ExitCode {
}
}
/// Lints one stdin buffer under the project config governing `--stdin-filename`
/// (or the working directory), applying CLI over config rule selection.
fn run_check_stdin(opts: &Options) -> Result<ExitCode, String> {
let (config, file_config) = stdin_config(opts)?;
let mut src = String::new();
std::io::stdin().read_to_string(&mut src).map_err(|e| format!("reading stdin: {e}"))?;
// A stdin buffer is one text with nothing around it: there is no census
// to build and no other file to ask about, so workspace rules stay off.
let select = lint::pick(&opts.select, file_config.lint_select.as_deref());
let ignore = lint::pick(&opts.ignore, file_config.lint_ignore.as_deref());
let rules = vlog_linter::select_rules(select, ignore, false).map_err(|e| {
let origin = file_config
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |p| p.display().to_string());
format!("{origin}: {e}")
})?;
let options = lint::rule_options(&file_config)?;
// A stdin buffer has one config file too — the one governing
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
// reaches it alongside `[lint] select` and `[lint.<rule>]`.
let external = lint::external_waivers(opts, std::iter::once(&file_config))?;
Ok(lint::check_stdin(opts, &src, &config, &rules, &options, &external))
}
fn run_stdin(opts: &Options) -> ExitCode {
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
let (config, _file_config) = match stdin_config(opts) {
@@ -170,15 +165,32 @@ fn run_stdin(opts: &Options) -> ExitCode {
let mut src = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut src) {
eprintln!("error: reading stdin: {e}");
if opts.output_format == OutputFormat::Json {
let info = FormatErrorInfo::io(&e);
let entries = [JsonEntry::error(name.to_string(), info)];
print_format_json(&entries, true, 0, 0, 0, 1);
}
return ExitCode::from(2);
}
let out = match format_contained(&src, &config, opts.lines.as_ref()) {
Ok(o) => o,
Err(e) => {
eprintln!("error: {name}: {e}");
Err(info) => {
eprintln!("error: {name}: {}", info.display);
if opts.output_format == OutputFormat::Json {
let entries = [JsonEntry::error(name.to_string(), info)];
print_format_json(&entries, true, 0, 0, 0, 1);
}
return ExitCode::from(2);
}
};
if opts.output_format == OutputFormat::Json {
let changed = usize::from(out != src);
let unchanged = usize::from(out == src);
let status = if changed > 0 { "would-reformat" } else { "unchanged" };
let entries = [JsonEntry::ok(name.to_string(), status, false)];
print_format_json(&entries, true, changed, unchanged, 0, 0);
return if changed > 0 { ExitCode::from(1) } else { ExitCode::SUCCESS };
}
if !opts.read_only() {
print!("{out}");
return ExitCode::SUCCESS;
@@ -218,31 +230,53 @@ fn run_files(opts: &Options) -> ExitCode {
let results: Vec<FileResult> =
jobs.par_iter().map(|(file, config, _)| process_file(file, config, opts, &cache)).collect();
let json = opts.output_format == OutputFormat::Json;
let mut entries = if json { Vec::with_capacity(results.len()) } else { Vec::new() };
let (mut changed, mut unchanged, mut errors, mut cached) = (0usize, 0usize, 0usize, 0usize);
for (index, result) in results.into_iter().enumerate() {
let (file, config, _) = &jobs[index];
if let Some(content) = result.clean {
cache.record(file, entry_for(content, config));
}
let name = || file.display().to_string();
match result.outcome {
Outcome::Unchanged => unchanged += 1,
Outcome::Unchanged => {
unchanged += 1;
if json {
entries.push(JsonEntry::ok(name(), "unchanged", false));
}
}
Outcome::Cached => {
unchanged += 1;
cached += 1;
if json {
entries.push(JsonEntry::ok(name(), "cached", true));
}
}
Outcome::Printed(text) => print!("{text}"),
Outcome::Changed(text) => {
changed += 1;
print!("{text}");
if json {
let status = if opts.read_only() { "would-reformat" } else { "reformatted" };
entries.push(JsonEntry::ok(name(), status, false));
} else {
print!("{text}");
}
}
Outcome::Failed(message) => {
Outcome::Failed(info) => {
errors += 1;
eprintln!("error: {message}");
eprintln!("error: {}: {}", file.display(), info.display);
if json {
entries.push(JsonEntry::error(name(), info));
}
}
}
}
cache.store();
if json {
print_format_json(&entries, opts.read_only(), changed, unchanged, cached, errors);
}
if !opts.stdout {
report(opts, changed, unchanged, cached, errors);
}
@@ -287,8 +321,8 @@ enum Outcome {
/// The file would change, or did. The text is the `--diff` hunk or the
/// `--check` line, and is empty when the file was rewritten in place.
Changed(String),
/// `<path>: <what went wrong>`. The file was left untouched.
Failed(String),
/// What went wrong while reading, formatting, or writing the file.
Failed(FormatErrorInfo),
}
/// Formats one file and, unless the run is read-only, writes it back.
@@ -298,7 +332,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
let name = file.display();
let src = match std::fs::read_to_string(file) {
Ok(s) => s,
Err(e) => return FileResult::plain(Outcome::Failed(format!("{name}: {e}"))),
Err(e) => return FileResult::plain(Outcome::Failed(FormatErrorInfo::io(&e))),
};
let hash = content_hash(src.as_bytes());
if cache.is_clean(file, entry_for(hash, config)) {
@@ -306,7 +340,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
}
let out = match format_contained(&src, config, opts.lines.as_ref()) {
Ok(o) => o,
Err(e) => return FileResult::plain(Outcome::Failed(format!("{name}: {e}"))),
Err(info) => return FileResult::plain(Outcome::Failed(info)),
};
if opts.stdout {
return FileResult::plain(Outcome::Printed(out));
@@ -320,7 +354,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
} else if opts.check {
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
FileResult::plain(Outcome::Failed(FormatErrorInfo::io(&e)))
} else {
// The bytes now on disk are formatted, so they are what the cache
// records — not the input's hash.
@@ -441,25 +475,7 @@ fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
/// best two names for it can be compared by. Neither is ever the path lucisv
/// reports: that stays the first spelling seen.
fn identity(cwd: &Path, path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path))
}
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
/// file share. Purely lexical, like `lucisv_core`'s own normalization — it
/// answers for paths that do not exist, where there is nothing to resolve.
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { 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
std::fs::canonicalize(path).unwrap_or_else(|_| normalize_under(cwd, path))
}
/// The settings for a buffer piped in on stdin: discovery anchors on
@@ -469,7 +485,7 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
/// which the resolved `Config` does not carry.
fn stdin_config(opts: &Options) -> Result<(Config, FileConfig), String> {
let mut discovery = Discovery::new(!opts.no_config);
let file = match opts.stdin_filename.as_deref() {
let file = match opts.stdin_filename.as_deref().filter(|s| !s.is_empty()) {
Some(name) => discovery.for_file(Path::new(name))?,
None => discovery.for_dir(Path::new("."))?,
};
@@ -500,6 +516,153 @@ fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, error
}
}
/// Structured error detail for `--output-format json` paired with the text
/// display string used on stderr.
#[derive(Debug, Clone, PartialEq, Eq)]
struct FormatErrorInfo {
category: &'static str,
line: Option<u32>,
column: Option<u32>,
message: String,
display: String,
}
impl FormatErrorInfo {
fn io(err: &std::io::Error) -> Self {
let message = err.to_string();
Self { category: "io-error", line: None, column: None, display: message.clone(), message }
}
fn panic(msg: &str) -> Self {
let message = format!("panicked while formatting: {msg}");
Self { category: "panic", line: None, column: None, display: message.clone(), message }
}
fn from_format(err: &FormatError) -> Self {
let display = err.to_string();
match err {
FormatError::Source(vlog_parser::Error::Lex(e)) => Self {
category: "lex-error",
line: Some(e.line),
column: Some(e.col),
message: e.message.clone(),
display,
},
FormatError::Source(vlog_parser::Error::Parse(e)) => Self {
category: "parse-error",
line: Some(e.line),
column: Some(e.col),
message: e.message.clone(),
display,
},
FormatError::Verification(v) => {
let (line, column) = verification_location(v);
Self {
category: "verification-error",
line,
column,
message: display.clone(),
display,
}
}
FormatError::Selection(msg) => Self {
category: "selection-error",
line: None,
column: None,
message: msg.clone(),
display,
},
}
}
}
fn verification_location(err: &VerificationError) -> (Option<u32>, Option<u32>) {
match err {
VerificationError::Lex { error, .. } => (Some(error.line), Some(error.col)),
VerificationError::Reparse(vlog_parser::Error::Lex(e)) => (Some(e.line), Some(e.col)),
VerificationError::Reparse(vlog_parser::Error::Parse(e)) => (Some(e.line), Some(e.col)),
VerificationError::Divergence { expected, got, .. } => {
expected.as_ref().or(got.as_ref()).map_or((None, None), |i| (Some(i.line), Some(i.col)))
}
VerificationError::NotConverged { line, .. } => (u32::try_from(*line).ok(), None),
}
}
struct JsonEntry {
filename: String,
status: &'static str,
cached: bool,
error: Option<FormatErrorInfo>,
}
impl JsonEntry {
fn ok(filename: String, status: &'static str, cached: bool) -> Self {
Self { filename, status, cached, error: None }
}
fn error(filename: String, info: FormatErrorInfo) -> Self {
Self { filename, status: "error", cached: false, error: Some(info) }
}
}
fn format_json_report(
entries: &[JsonEntry],
read_only: bool,
changed: usize,
unchanged: usize,
cached: usize,
errors: usize,
) -> String {
let (status, exit_code) = if errors > 0 {
("error", 2)
} else if read_only && changed > 0 {
("would-reformat", 1)
} else if changed > 0 {
("reformatted", 0)
} else {
("ok", 0)
};
let items: Vec<String> = entries
.iter()
.map(|entry| {
let err = match &entry.error {
Some(info) => format!(
"{{\"category\":{},\"line\":{},\"column\":{},\"message\":{}}}",
lint::quote(info.category),
info.line.map_or_else(|| "null".to_string(), |n| n.to_string()),
info.column.map_or_else(|| "null".to_string(), |n| n.to_string()),
lint::quote(&info.message),
),
None => "null".to_string(),
};
format!(
"{{\"filename\":{},\"status\":{},\"cached\":{},\"error\":{err}}}",
lint::quote(&entry.filename),
lint::quote(entry.status),
entry.cached,
)
})
.collect();
format!(
"{{\"status\":{},\"exit_code\":{exit_code},\
\"summary\":{{\"changed\":{changed},\"unchanged\":{unchanged},\"cached\":{cached},\"errors\":{errors}}},\
\"files\":[{}]}}",
lint::quote(status),
items.join(","),
)
}
fn print_format_json(
entries: &[JsonEntry],
read_only: bool,
changed: usize,
unchanged: usize,
cached: usize,
errors: usize,
) {
println!("{}", format_json_report(entries, read_only, changed, unchanged, cached, errors));
}
/// Formats one source text — all of it, or only the constructs meeting
/// `lines` — reporting a panic inside the formatter as an ordinary error so
/// the rest of the run can continue.
@@ -507,14 +670,14 @@ fn format_contained(
src: &str,
config: &Config,
lines: Option<&LineRanges>,
) -> Result<String, String> {
) -> Result<String, FormatErrorInfo> {
match catch_panic(|| match lines {
Some(lines) => format_range(src, config, lines),
None => format_source(src, config),
}) {
Ok(Ok(out)) => Ok(out),
Ok(Err(e)) => Err(e.to_string()),
Err(msg) => Err(format!("panicked while formatting: {msg}")),
Ok(Err(e)) => Err(FormatErrorInfo::from_format(&e)),
Err(msg) => Err(FormatErrorInfo::panic(&msg)),
}
}
@@ -661,11 +824,54 @@ mod tests {
#[test]
fn format_contained_reports_parse_errors() {
let err = format_contained("module", &Config::default(), None).unwrap_err();
assert!(err.contains("parse error"), "{err}");
assert_eq!(err.category, "parse-error");
assert!(err.display.contains("parse error"), "{}", err.display);
// A range run parses just as strictly: it cannot rescue broken input.
let lines = LineRanges::parse("1").expect("range");
let err = format_contained("module", &Config::default(), Some(&lines)).unwrap_err();
assert!(err.contains("parse error"), "{err}");
assert_eq!(err.category, "parse-error");
assert!(err.display.contains("parse error"), "{}", err.display);
}
#[test]
fn format_error_info_classifies_lex_verification_io_and_panic() {
let lex = format_contained("module m;\n int é;\nendmodule\n", &Config::default(), None)
.unwrap_err();
assert_eq!(lex.category, "lex-error");
assert_eq!((lex.line, lex.column), (Some(2), Some(7)));
let io = FormatErrorInfo::io(&std::io::Error::new(std::io::ErrorKind::NotFound, "gone"));
assert_eq!(io.category, "io-error");
assert_eq!((io.line, io.column), (None, None));
let panic_err = FormatErrorInfo::panic("boom");
assert_eq!(panic_err.category, "panic");
assert!(panic_err.message.contains("boom"));
let ver = FormatErrorInfo::from_format(&FormatError::Verification(
VerificationError::NotConverged {
line: 12,
first: "a".to_string(),
second: "b".to_string(),
},
));
assert_eq!(ver.category, "verification-error");
assert_eq!((ver.line, ver.column), (Some(12), None));
let report = format_json_report(
&[
JsonEntry::ok("a.sv".to_string(), "unchanged", false),
JsonEntry::error("b.sv".to_string(), lex),
],
true,
0,
1,
0,
1,
);
assert!(report.contains("\"status\":\"error\""), "{report}");
assert!(report.contains("\"exit_code\":2"), "{report}");
assert!(report.contains("\"category\":\"lex-error\""), "{report}");
}
}
+222 -1
View File
@@ -1192,7 +1192,8 @@ fn flags_of_the_other_tool_are_rejected() {
for args in [
vec!["--fix", &path],
vec!["--select", "no-tabs", &path],
vec!["--output-format", "json", &path],
vec!["--ignore", "no-tabs", &path],
vec!["--waiver-file", "a.waiver", &path],
] {
let out = run(&args);
assert_eq!(code(&out), 2, "{args:?} must not be accepted by the formatter");
@@ -2149,8 +2150,10 @@ fn a_stdin_buffer_reads_the_rule_options_too() {
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
let name = format!("{}/m.sv", dir.root());
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
assert_eq!(code(&out), 0, "the config's pattern accepts it: {}", stderr(&out));
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
assert_eq!(code(&plain), 1, "without the config, macro-name-style fires: {}", stderr(&plain));
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
}
@@ -2466,4 +2469,222 @@ fn text_that_merely_says_package_changes_no_finding() {
);
}
// ----------------------------------------------------------------------
// Stdin config discovery across format/check and `--output-format json`
// (Round 5A: #11, #55)
// ----------------------------------------------------------------------
fn run_in_with_stdin(dir: &TempDir, args: &[&str], input: &str) -> Output {
let mut child = Command::new(LUCISV)
.args(with_no_cache(args))
.current_dir(&dir.path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn lucisv");
feed(&mut child, input);
child.wait_with_output().expect("run lucisv")
}
#[test]
fn stdin_discovers_config_relative_to_stdin_filename_across_cwd_and_subcommands() {
let dir = TempDir::new("stdin-cwd-discovery");
dir.write("lucisv.toml", "indent = 4\n[lint]\nignore = [\"no-tabs\"]\n");
dir.write("sub/lucisv.toml", "indent = 6\n[lint]\nselect = [\"no-tabs\"]\n");
let sub_dir = TempDir { path: dir.path.join("sub") };
// From root CWD, relative `sub/new.sv` (which does not exist on disk)
// picks up `sub/lucisv.toml` for both format and check.
let fmt_sub =
run_in_with_stdin(&dir, &["format", "--stdin-filename", "sub/new.sv", "-"], UNINDENTED);
assert_eq!(code(&fmt_sub), 0, "{}", stderr(&fmt_sub));
assert_eq!(stdout(&fmt_sub), "module m;\n wire x;\nendmodule\n");
let chk_sub = run_in_with_stdin(
&dir,
&["check", "--stdin-filename", "sub/new.sv", "-"],
"module new;\n\twire a;\nendmodule\n",
);
assert_eq!(code(&chk_sub), 1, "{}", stderr(&chk_sub));
assert!(stdout(&chk_sub).contains("[no-tabs]"), "{}", stdout(&chk_sub));
assert!(
!stdout(&chk_sub).contains("module-filename"),
"select in sub/lucisv.toml governs stdin"
);
// From `sub/` CWD, `../rtl/m.sv` climbs back out of `sub/` to root's config,
// ignoring `sub/lucisv.toml` (`indent = 6`, `select = ["no-tabs"]`).
let fmt_parent =
run_in_with_stdin(&sub_dir, &["--stdin-filename", "../rtl/m.sv", "-"], UNINDENTED);
assert_eq!(code(&fmt_parent), 0, "{}", stderr(&fmt_parent));
assert_eq!(stdout(&fmt_parent), INDENT_4);
let chk_parent = run_in_with_stdin(
&sub_dir,
&["check", "--stdin-filename", "../rtl/m.sv", "-"],
"module m;\n\twire a;\nendmodule\n",
);
assert_eq!(code(&chk_parent), 0, "parent config ignores no-tabs: {}", stderr(&chk_parent));
assert_eq!(stdout(&chk_parent), "");
// Do not drop `sub_dir` (it shares `dir.path`); forget it safely.
std::mem::forget(sub_dir);
// Unknown rule in `lucisv.toml`'s `[lint] select` still fails stdin check with exit 2.
dir.write("bad_lint/lucisv.toml", "[lint]\nselect = [\"no-such-rule\"]\n");
let bad_rule =
run_in_with_stdin(&dir, &["check", "--stdin-filename", "bad_lint/m.sv", "-"], FORMATTED);
assert_eq!(code(&bad_rule), 2);
assert!(stderr(&bad_rule).contains("unknown rule: no-such-rule"), "{}", stderr(&bad_rule));
// An empty `--stdin-filename` is rejected explicitly instead of walking CWD's parent.
let empty = run_with_stdin(&["--stdin-filename", "", "-"], UNINDENTED);
assert_eq!(code(&empty), 2);
assert!(
stderr(&empty).contains("--stdin-filename requires a non-empty path"),
"{}",
stderr(&empty)
);
}
#[test]
fn format_output_format_json_covers_clean_dirty_inplace_cached_and_errors() {
let dir = TempDir::new("format-json");
let clean = dir.write("a_clean.sv", FORMATTED);
let dirty = dir.write("b_dirty.sv", UNFORMATTED);
let bad_parse = dir.write("c_parse.sv", UNPARSEABLE);
let bad_lex = dir.write("d_lex.sv", "module m;\n int é;\nendmodule\n");
// Clean (--check): exit 0, unchanged.
let out = run(&["--check", "--output-format", "json", &clean]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let text = stdout(&out);
assert!(text.contains("\"status\":\"ok\""), "{text}");
assert!(text.contains("\"exit_code\":0"), "{text}");
assert!(text.contains("\"changed\":0,\"unchanged\":1,\"cached\":0,\"errors\":0"), "{text}");
assert!(text.contains("\"status\":\"unchanged\",\"cached\":false,\"error\":null"), "{text}");
// Dirty (--check): exit 1, would-reformat, file untouched.
let out = run(&["--check", "--output-format", "json", &dirty]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let text = stdout(&out);
assert!(text.contains("\"status\":\"would-reformat\""), "{text}");
assert!(text.contains("\"exit_code\":1"), "{text}");
assert!(text.contains("\"changed\":1,\"unchanged\":0,\"cached\":0,\"errors\":0"), "{text}");
assert!(
text.contains("\"status\":\"would-reformat\",\"cached\":false,\"error\":null"),
"{text}"
);
assert_eq!(dir.read("b_dirty.sv"), UNFORMATTED);
// Parse error: exit 2, category parse-error with line/column/message.
let out = run(&["--check", "--output-format", "json", &bad_parse]);
assert_eq!(code(&out), 2);
let text = stdout(&out);
assert!(text.contains("\"status\":\"error\""), "{text}");
assert!(text.contains("\"exit_code\":2"), "{text}");
assert!(text.contains("\"category\":\"parse-error\""), "{text}");
assert!(text.contains("\"line\":2,\"column\":1"), "{text}");
assert!(text.contains("expected identifier"), "{text}");
assert_eq!(dir.read("c_parse.sv"), UNPARSEABLE);
// Lex error: exit 2, category lex-error with line/column/message.
let out = run(&["--check", "--output-format", "json", &bad_lex]);
assert_eq!(code(&out), 2);
let text = stdout(&out);
assert!(text.contains("\"category\":\"lex-error\""), "{text}");
assert!(text.contains("\"line\":2,\"column\":7"), "{text}");
// Mixed directory run: deterministic across thread counts, exit 2 wins.
let parallel = run(&["--check", "--output-format", "json", &dir.root()]);
let serial = run(&["--threads", "1", "--check", "--output-format", "json", &dir.root()]);
assert_eq!(code(&parallel), 2);
assert_eq!(parallel.stdout, serial.stdout);
let text = stdout(&parallel);
assert!(text.contains("\"changed\":1,\"unchanged\":1,\"cached\":0,\"errors\":2"), "{text}");
assert_eq!(text.lines().count(), 1, "stdout must be one JSON document: {text}");
// In-place formatting (default format mode without --check) with JSON + cache.
let cache = dir.cache();
let out = run_raw(&["--output-format", "json", "--cache-dir", &cache, &dirty]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
let text = stdout(&out);
assert!(text.contains("\"status\":\"reformatted\""), "{text}");
assert!(text.contains("\"exit_code\":0"), "{text}");
assert_eq!(dir.read("b_dirty.sv"), FORMATTED);
let cached_out =
run_raw(&["--check", "--output-format", "json", "--cache-dir", &cache, &dirty]);
assert_eq!(code(&cached_out), 0, "{}", stderr(&cached_out));
let text = stdout(&cached_out);
assert!(text.contains("\"status\":\"cached\",\"cached\":true"), "{text}");
assert!(text.contains("\"unchanged\":1,\"cached\":1"), "{text}");
}
#[test]
fn format_output_format_json_works_on_stdin_check_and_rejects_conflicts() {
let out = run_with_stdin(&["--check", "--output-format", "json", "-"], FORMATTED);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(
stdout(&out).contains("\"filename\":\"<stdin>\",\"status\":\"unchanged\""),
"{}",
stdout(&out)
);
let out = run_with_stdin(
&["--check", "--output-format", "json", "--stdin-filename", "rtl/top.sv", "-"],
UNFORMATTED,
);
assert_eq!(code(&out), 1);
let text = stdout(&out);
assert!(text.contains("\"filename\":\"rtl/top.sv\",\"status\":\"would-reformat\""), "{text}");
assert!(text.contains("\"exit_code\":1"), "{text}");
let out = run_with_stdin(&["--check", "--output-format", "json", "-"], UNPARSEABLE);
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("\"category\":\"parse-error\""), "{}", stdout(&out));
let out = run_with_stdin(
&["--check", "--output-format", "json", "-"],
"module m;\n int é;\nendmodule\n",
);
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("\"category\":\"lex-error\""), "{}", stdout(&out));
let dir = TempDir::new("format-json-conflicts");
let file = dir.write("a.sv", UNFORMATTED);
for bad in [
vec!["--diff", "--output-format", "json", &file],
vec!["--stdout", "--output-format", "json", &file],
vec!["--output-format", "json", "-"],
] {
let out = run_with_stdin(&bad, UNFORMATTED);
assert_eq!(code(&out), 2, "{bad:?}");
}
}
#[cfg(unix)]
#[test]
fn format_output_format_json_reports_io_error_on_unreadable_file() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("format-json-io");
let locked = dir.write("locked.sv", FORMATTED);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).expect("chmod");
if std::fs::read_to_string(&locked).is_ok() {
let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755));
eprintln!("skipped: a mode-000 file is readable by this user (root?)");
return;
}
let out = run(&["--check", "--output-format", "json", &locked]);
let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o644));
assert_eq!(code(&out), 2);
let text = stdout(&out);
assert!(text.contains("\"status\":\"error\""), "{text}");
assert!(text.contains("\"exit_code\":2"), "{text}");
assert!(text.contains("\"category\":\"io-error\""), "{text}");
assert!(text.contains("\"line\":null,\"column\":null"), "{text}");
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+3 -21
View File
@@ -10,7 +10,7 @@
//! reasoning behind not taking a TOML dependency.
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
/// Config file names, in the order a directory is probed.
pub const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
@@ -377,7 +377,7 @@ impl Discovery {
if !self.enabled {
return Ok(FileConfig::default());
}
let absolute = self.absolute(path);
let absolute = crate::path::normalize_under(&self.cwd, path);
match absolute.parent() {
Some(dir) => self.for_dir(dir),
None => Ok(FileConfig::default()),
@@ -389,7 +389,7 @@ impl Discovery {
if !self.enabled {
return Ok(FileConfig::default());
}
let start = self.absolute(dir);
let start = crate::path::normalize_under(&self.cwd, dir);
let mut cursor = start.as_path();
// Directories that resolve to the same answer as `cursor` does.
let mut chain: Vec<PathBuf> = Vec::new();
@@ -416,24 +416,6 @@ impl Discovery {
}
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> {
+5 -23
View File
@@ -11,7 +11,7 @@
//! a warning for each problem. See `docs/features/filelist/README.md`.
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
/// How deep `-f` may nest before the reader stops descending.
///
@@ -63,7 +63,7 @@ fn read_with(path: &Path, env: &dyn Fn(&str) -> Option<String>) -> Result<Fileli
listed: HashSet::new(),
depth: 0,
};
let normalized = reader.normalize(path);
let normalized = crate::path::normalize_under(&reader.cwd, path);
reader.seen.insert(normalized);
reader.filelist(path, &text);
Ok(reader.out)
@@ -115,7 +115,7 @@ impl Reader<'_> {
expecting_filelist = true;
} else if let Some(rest) = token.strip_prefix("+incdir+") {
for item in rest.split('+').filter(|s| !s.is_empty()) {
let resolved = self.normalize(&dir.join(item));
let resolved = crate::path::normalize_under(&self.cwd, &dir.join(item));
self.out.incdirs.push(resolved);
}
} else if let Some(rest) = token.strip_prefix("+define+") {
@@ -151,7 +151,7 @@ impl Reader<'_> {
return;
}
let path = dir.join(token);
let normalized = self.normalize(&path);
let normalized = crate::path::normalize_under(&self.cwd, &path);
if !self.seen.insert(normalized) {
self.warn(line, format!("filelist `{token}` was already included, skipping it"));
return;
@@ -173,7 +173,7 @@ impl Reader<'_> {
self.warn(line, format!("no such file `{token}`, skipping it"));
return;
}
let normalized = self.normalize(&path);
let normalized = crate::path::normalize_under(&self.cwd, &path);
if self.listed.insert(normalized.clone()) {
self.out.files.push(normalized);
}
@@ -219,24 +219,6 @@ impl Reader<'_> {
fn warn(&mut self, line: &Line<'_>, what: String) {
self.out.warnings.push(format!("{}:{}: {what}", line.file.display(), line.number));
}
/// Fold `.`/`..` away and resolve against the current directory, so two
/// spellings of one file are one entry. Symlinks are deliberately not
/// resolved, matching `config::Discovery`'s lexical rule.
fn normalize(&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
}
}
/// Where a warning happened.
+3 -1
View File
@@ -11,7 +11,8 @@
//! an EDA project already does, from a `.f` file. `atomic` is the one write
//! path all of them share: nothing here ever truncates a file it is
//! replacing. `diff` is the unified diff the CLI's `--diff` and the MCP
//! server's `dry_run` both print. See
//! server's `dry_run` both print, and `path` holds the shared lexical `.`/`..`
//! path normalization. See
//! `docs/features/lucisv-core-lift/README.md`, and
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
//! for the rules themselves.
@@ -21,6 +22,7 @@ pub mod cache;
pub mod config;
pub mod diff;
pub mod filelist;
pub mod path;
pub mod walk;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+144
View File
@@ -0,0 +1,144 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Lexical path normalization shared across `lucisv_core`, `lucisv`, and
//! `lucisv_server`.
//!
//! Paths are folded lexically (`.` and `..` resolved component-by-component)
//! without calling `std::fs::canonicalize` so symlinks are never followed and
//! non-existent paths (such as `--stdin-filename` or rename targets) behave
//! identically to existing ones.
use std::path::{Component, Path, PathBuf};
/// Folds `.` and `..` components out of `path` lexically, without touching the
/// filesystem.
///
/// - Leading or excess `..` on a relative path (and after an unrooted Windows
/// drive prefix such as `C:`) are preserved.
/// - `..` immediately after a root directory (`/` on Unix, `C:\` or
/// `\\server\share\` on Windows) is discarded because traversal cannot climb
/// above a root.
/// - A non-empty relative path whose components all cancel (`"."`, `"a/.."`)
/// normalizes to `"."`; an empty path stays empty.
pub fn normalize(path: &Path) -> PathBuf {
let mut parts: Vec<Component<'_>> = Vec::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => match parts.last() {
Some(Component::Normal(_)) => {
parts.pop();
}
Some(Component::RootDir) => {}
Some(Component::Prefix(_)) | Some(Component::ParentDir) | None => {
parts.push(Component::ParentDir);
}
// `CurDir` is never pushed into `parts`.
Some(Component::CurDir) => {}
},
other => parts.push(other),
}
}
if parts.is_empty() {
if path.as_os_str().is_empty() {
return PathBuf::new();
}
return PathBuf::from(".");
}
let mut out = PathBuf::new();
for part in parts {
out.push(part);
}
out
}
/// Resolves `path` against `base` when `path` is relative and normalizes the
/// result lexically.
///
/// An absolute `path` ignores `base` and is normalized directly. On Windows, a
/// root-relative (`\foo`) or drive-relative (`D:foo`) path is joined via
/// [`Path::join`] before normalizing, preserving drive prefixes cleanly.
pub fn normalize_under(base: &Path, path: &Path) -> PathBuf {
if path.is_absolute() {
normalize(path)
} else {
normalize(&base.join(path))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn folds_dots_and_preserves_leading_parent_dirs() {
assert_eq!(normalize(Path::new("")), PathBuf::new());
assert_eq!(normalize(Path::new(".")), PathBuf::from("."));
assert_eq!(normalize(Path::new("././.")), PathBuf::from("."));
assert_eq!(normalize(Path::new("a/..")), PathBuf::from("."));
assert_eq!(normalize(Path::new("a/./b/../c")), PathBuf::from("a/c"));
assert_eq!(normalize(Path::new("./rtl/../rtl/a.sv")), PathBuf::from("rtl/a.sv"));
assert_eq!(normalize(Path::new("../a")), PathBuf::from("../a"));
assert_eq!(normalize(Path::new("a/../../b")), PathBuf::from("../b"));
assert_eq!(normalize(Path::new("../..")), PathBuf::from("../.."));
}
#[test]
fn normalize_under_joins_relative_paths_and_leaves_absolute_ones() {
let base = if cfg!(windows) { Path::new(r"C:\work\proj") } else { Path::new("/work/proj") };
let abs =
if cfg!(windows) { Path::new(r"D:\other\a.sv") } else { Path::new("/other/a.sv") };
assert_eq!(normalize_under(base, Path::new("rtl/./a.sv")), base.join("rtl").join("a.sv"));
assert_eq!(
normalize_under(base, Path::new("../shared/a.sv")),
base.parent().expect("parent").join("shared").join("a.sv")
);
assert_eq!(normalize_under(base, Path::new(".")), base);
assert_eq!(normalize_under(base, Path::new("")), base);
assert_eq!(normalize_under(base, abs), abs);
}
#[cfg(unix)]
#[test]
fn unix_roots_clamp_excess_parent_dirs() {
assert_eq!(normalize(Path::new("/")), PathBuf::from("/"));
assert_eq!(normalize(Path::new("/..")), PathBuf::from("/"));
assert_eq!(normalize(Path::new("/./a/../../b//c/")), PathBuf::from("/b/c"));
assert_eq!(
normalize_under(Path::new("/a/b"), Path::new("/x/../../y")),
PathBuf::from("/y")
);
}
#[cfg(windows)]
#[test]
fn windows_prefixes_and_roots_clamp_or_preserve_parent_dirs() {
assert_eq!(normalize(Path::new(r"C:\")), PathBuf::from(r"C:\"));
assert_eq!(normalize(Path::new(r"C:\..")), PathBuf::from(r"C:\"));
assert_eq!(normalize(Path::new(r"C:\a\..\..\b\c\")), PathBuf::from(r"C:\b\c"));
assert_eq!(
normalize(Path::new(r"\\server\share\a\..\..\b")),
PathBuf::from(r"\\server\share\b")
);
assert_eq!(normalize(Path::new(r"\a\..\..\b")), PathBuf::from(r"\b"));
// Drive-relative paths have no root directory, so climbing past the
// prefix keeps `..` rather than turning into a rooted path.
assert_eq!(normalize(Path::new(r"C:a\..\..\b")), PathBuf::from(r"C:..\b"));
assert_eq!(normalize(Path::new(r"C:.")), PathBuf::from(r"C:"));
assert_eq!(
normalize_under(Path::new(r"C:\work\proj"), Path::new(r"\other\..\a.sv")),
PathBuf::from(r"C:\a.sv")
);
assert_eq!(
normalize_under(Path::new(r"C:\work\proj"), Path::new(r"D:rtl\..\a.sv")),
PathBuf::from(r"D:a.sv")
);
assert_eq!(
normalize_under(Path::new(r"C:\work\proj"), Path::new(r"D:\x\..\..\y.sv")),
PathBuf::from(r"D:\y.sv")
);
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+4 -2
View File
@@ -419,9 +419,11 @@ mod tests {
assert!(typed.contains("`b` takes its direction"), "{typed}");
let arm = refusal(&design("`ifdef X\n input logic a,\n`endif\n output logic y"), "a");
assert!(arm.contains("inside an `ifdef arm"), "{arm}");
let hidden =
let attributed =
refusal(&design(" input logic [7:0] a,\n (* keep *) b,\n output logic y"), "a");
assert!(hidden.contains("`m`'s port list holds `(* keep *) b`"), "{hidden}");
assert!(attributed.contains("`b` takes its direction"), "{attributed}");
let hidden = refusal(&design(" input logic [7:0] a,\n 123 b,\n output logic y"), "a");
assert!(hidden.contains("`m`'s port list holds `123 b`"), "{hidden}");
let mut files = design(" input logic a,\n output logic y");
files[1].1 =
"module top(input logic a, en, output logic y);\n m u_m (a, y);\nendmodule\n".into();
+4 -17
View File
@@ -10,7 +10,7 @@
//! `docs/features/include-nav/README.md`.
use std::collections::{HashMap, HashSet};
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
use lsp_types::{DocumentLink, Location, Range, Uri};
use vlog_parser::TextRange;
@@ -518,22 +518,9 @@ impl IncludeGraph {
/// compares equal to the same file's path in the index. Symlinks are
/// deliberately not resolved, matching `lucisv_core`'s lexical rule.
///
/// Public since 2026-08-27 so `file_ops.rs` folds a renamed file's path the
/// same way a resolved include is folded — the two are compared, and a fourth
/// private copy of this loop is the one thing that guarantees they disagree.
pub fn normalize(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
/// Re-exported from [`lucisv_core::path::normalize`] so `file_ops.rs` folds a
/// renamed file's path with the same implementation a resolved include uses.
pub use lucisv_core::path::normalize;
// ----------------------------------------------------------------------
// the two capabilities
+123 -55
View File
@@ -28,16 +28,33 @@
//! the name, so only [`resolve_style`] pays for it.
//! `docs/features/format-styles/README.md` has the sweep that checks both.
use crate::format::{format_styled, Config, FormatError};
use std::collections::HashMap;
use crate::fence::Region;
use crate::format::{
parse_once, render_parsed, verify_rendered, Config, FormatError, ParsedSource,
};
use crate::style::{Style, PRESETS};
use vlog_parser::ast::SourceFile;
/// The name the setting spells auto with.
pub(crate) const NAME: &str = "auto";
/// Result of parse-once preset competition: winning preset index, rendered
/// bytes, the single parsed input AST (`source`), and — when the output
/// differed from `source` and ran verification — the parsed output AST & fence
/// regions ready for `canonical`.
struct ClosestMatch {
index: usize,
output: String,
parsed: ParsedSource,
out_parsed: Option<(SourceFile, Vec<Region>)>,
}
/// The output of the preset closest to `source`, or — when no preset can
/// format it — the first preset's error.
pub(crate) fn format_closest(source: &str, config: &Config) -> Result<String, FormatError> {
closest(source, config).map(|(_, output)| output)
closest_inner(source, config).map(|m| m.output)
}
/// [`crate::format_source`] under auto, also handing back the preset whose
@@ -46,20 +63,19 @@ pub(crate) fn format_closest(source: &str, config: &Config) -> Result<String, Fo
/// one that won, not [`resolve_style`]'s canonical name; both leave the
/// output exactly as it is.
pub fn format_auto(source: &str, config: &Config) -> Result<(String, Style), FormatError> {
closest(source, config).map(|(index, output)| (output, PRESETS[index]))
closest_inner(source, config).map(|m| (m.output, PRESETS[m.index]))
}
/// `config` made concrete for the range and selection formatters: unchanged
/// unless it asks for auto, and then the closest preset of the *whole* file.
/// A file no preset can format — one with a parse error — gets the default's
/// layout. No naming pass: the output does not depend on the name.
pub(crate) fn concrete(source: &str, config: &Config) -> Config {
/// `config` made concrete for the range and selection formatters, paired with
/// the already-parsed `source` when available so callers avoid re-parsing.
/// A file no preset can format gets the default's layout (`None` parsed tree).
pub(crate) fn resolve_concrete(source: &str, config: &Config) -> (Config, Option<ParsedSource>) {
if !config.auto_style {
return config.clone();
return (config.clone(), None);
}
match closest(source, config) {
Ok((index, _)) => fixed(config, PRESETS[index]),
Err(_) => fixed(config, PRESETS[0]),
match closest_inner(source, config) {
Ok(m) => (fixed(config, PRESETS[m.index]), Some(m.parsed)),
Err(_) => (fixed(config, PRESETS[0]), None),
}
}
@@ -71,48 +87,75 @@ pub fn resolve_style(source: &str, config: &Config) -> Config {
if !config.auto_style {
return config.clone();
}
match closest(source, config) {
Ok((index, output)) => fixed(config, PRESETS[canonical(&output, config, index)]),
match closest_inner(source, config) {
Ok(m) => {
let idx = match m.out_parsed {
// `d == (0, 0)` stopped at the earliest preset whose render
// equals `source`, so no earlier preset can also match `output`.
None => m.index,
Some((ref out_file, ref out_regions)) => {
canonical_parsed(&m.output, out_file, out_regions, config, m.index)
}
};
fixed(config, PRESETS[idx])
}
Err(_) => fixed(config, PRESETS[0]),
}
}
/// The index of the closest preset and its output. Stops at the first
/// preset that leaves `source` exactly as it is: nothing can be closer.
fn closest(source: &str, config: &Config) -> Result<(usize, String), FormatError> {
let mut best: Option<((usize, usize), usize, String)> = None;
let mut first_error = None;
/// Lex and parse `source` once, render every preset over that single AST, pick
/// the closest output in `(distance, index)` order, and run safety verification
/// on the winner alone (falling back only if a candidate fails verification).
fn closest_inner(source: &str, config: &Config) -> Result<ClosestMatch, FormatError> {
let parsed = parse_once(source).map_err(FormatError::Source)?;
let mut counter: Option<LineCounter<'_>> = None;
let mut candidates: Vec<((usize, usize), usize, String)> = Vec::with_capacity(PRESETS.len());
for (index, preset) in PRESETS.into_iter().enumerate() {
match format_styled(source, &fixed(config, preset)) {
Ok(output) => {
let d = distance(source, &output);
if best.as_ref().is_none_or(|(least, _, _)| d < *least) {
best = Some((d, index, output));
}
if d == (0, 0) {
break;
}
}
Err(e) => {
first_error.get_or_insert(e);
let output = render_parsed(source, &parsed.file, &parsed.regions, &fixed(config, preset));
if output == source {
return Ok(ClosestMatch { index, output, parsed, out_parsed: None });
}
let d = (counter.get_or_insert_with(|| LineCounter::new(source)).apart(&output), 1);
candidates.push((d, index, output));
}
candidates.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
let mut errors: Vec<(usize, FormatError)> = Vec::new();
for (_, index, output) in candidates {
match verify_rendered(source, &parsed.items, &output, &fixed(config, PRESETS[index])) {
Ok(out_parsed) => {
return Ok(ClosestMatch { index, output, parsed, out_parsed: Some(out_parsed) });
}
Err(e) => errors.push((index, e)),
}
}
match (best, first_error) {
(Some((_, index, output)), _) => Ok((index, output)),
(None, Some(e)) => Err(e),
// Only reachable with no presets at all; there is always one.
(None, None) => format_styled(source, &fixed(config, PRESETS[0])).map(|out| (0, out)),
// Match the sequential contract: return the error from the earliest preset.
match errors.into_iter().min_by_key(|(idx, _)| *idx) {
Some((_, e)) => Err(e),
None => {
let output =
render_parsed(source, &parsed.file, &parsed.regions, &fixed(config, PRESETS[0]));
let out_parsed =
verify_rendered(source, &parsed.items, &output, &fixed(config, PRESETS[0]))?;
Ok(ClosestMatch { index: 0, output, parsed, out_parsed: Some(out_parsed) })
}
}
}
/// The earliest preset, up to `chosen`, that leaves `output` exactly as it
/// is — the one a second run over `output` picks. `chosen` itself always
/// qualifies: its output is a fixed point of it by the convergence check.
fn canonical(output: &str, config: &Config, chosen: usize) -> usize {
/// Earliest preset up to `chosen` whose render of `output` leaves it
/// unchanged, reusing `out_file` and `out_regions` with zero extra parses.
fn canonical_parsed(
output: &str,
out_file: &SourceFile,
out_regions: &[Region],
config: &Config,
chosen: usize,
) -> usize {
(0..chosen)
.find(|&i| {
format_styled(output, &fixed(config, PRESETS[i])).is_ok_and(|again| again == output)
render_parsed(output, out_file, out_regions, &fixed(config, PRESETS[i])) == output
})
.unwrap_or(chosen)
}
@@ -122,29 +165,54 @@ fn fixed(config: &Config, preset: Style) -> Config {
Config { style: preset, auto_style: false, ..config.clone() }
}
/// Multiset symmetric line difference against a pre-indexed `source`, reusing
/// one per-line scratch counter across all preset candidates.
struct LineCounter<'a> {
base: HashMap<&'a str, usize>,
total: usize,
seen: HashMap<&'a str, usize>,
}
impl<'a> LineCounter<'a> {
fn new(source: &'a str) -> Self {
let mut base = HashMap::new();
let mut total = 0usize;
for line in source.lines() {
*base.entry(line).or_insert(0) += 1;
total += 1;
}
Self { seen: HashMap::with_capacity(base.len()), base, total }
}
fn apart(&mut self, other: &str) -> usize {
self.seen.clear();
let mut b_total = 0usize;
let mut matched = 0usize;
for line in other.lines() {
b_total += 1;
if let Some((&key, &limit)) = self.base.get_key_value(line) {
let count = self.seen.entry(key).or_insert(0);
if *count < limit {
*count += 1;
matched += 1;
}
}
}
(self.total + b_total).saturating_sub(2 * matched)
}
}
/// How far `output` is from `source`: the number of lines whose bytes
/// change — lines either text has that the other lacks, indentation
/// included — then, to break a tie, whether the texts differ at all. The
/// pair is `(0, 0)` exactly when the two are equal, which is the whole of the
/// idempotency argument above.
#[cfg(test)]
fn distance(source: &str, output: &str) -> (usize, usize) {
if source == output {
return (0, 0);
}
(lines_apart(source.lines(), output.lines()), 1)
}
/// The size of the multiset difference between two runs of lines: a line
/// moved elsewhere costs nothing.
fn lines_apart<'a>(a: impl Iterator<Item = &'a str>, b: impl Iterator<Item = &'a str>) -> usize {
let mut counts: std::collections::HashMap<&str, isize> = std::collections::HashMap::new();
for line in a {
*counts.entry(line).or_default() += 1;
}
for line in b {
*counts.entry(line).or_default() -= 1;
}
counts.values().map(|n| n.unsigned_abs()).sum()
(LineCounter::new(source).apart(output), 1)
}
#[cfg(test)]
+100 -54
View File
@@ -12,7 +12,7 @@ use crate::style::Placement;
use vlog_parser::ast::*;
use vlog_parser::token::Comment;
use super::comment::trailing_ends_line;
use super::comment::{is_line_comment, trailing_ends_line};
use super::Fmt;
/// What goes in front of a keyword the style places: one space, or a line
@@ -24,6 +24,17 @@ pub(super) fn before_keyword(placement: Placement) -> Doc {
}
}
/// Borrowed fields of a [`StmtKind::If`] branch chain.
pub(super) struct IfParts<'s> {
pub(super) qualifier: &'s Option<String>,
pub(super) after_kw: &'s [Comment],
pub(super) cond: &'s Expr,
pub(super) then: &'s Stmt,
pub(super) else_directives: &'s [ListDirective],
pub(super) else_comments: &'s [Comment],
pub(super) els: &'s Option<Box<Stmt>>,
}
impl<'a> Fmt<'a> {
/// Whether an `else` may follow an `end` on the same line — an `end`
/// with a `: label` after it asks `else_after_label` instead.
@@ -33,59 +44,83 @@ impl<'a> Fmt<'a> {
style.else_keyword == Placement::SameLine && placement == Placement::SameLine
}
pub(super) fn if_stmt(
/// Emit any directives and comments written between a `then` branch and
/// `else`, then the `else` keyword (or `else if `) with cuddling or break.
fn push_else_keyword(
&self,
qualifier: &Option<String>,
after_kw: &[Comment],
cond: &Expr,
then: &Stmt,
docs: &mut Vec<Doc>,
cuddle: bool,
else_directives: &[ListDirective],
else_comments: &[Comment],
els: &Option<Box<Stmt>>,
) -> Doc {
kw: &str,
) {
if !else_directives.is_empty() || !else_comments.is_empty() {
for d in else_directives {
docs.push(if d.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
docs.extend(self.leading(&d.meta));
docs.push(self.raw_text(&d.raw));
docs.extend(self.trailing(&d.meta));
}
for c in else_comments {
docs.push(Doc::HardLine);
docs.push(self.comment(c));
}
docs.push(Doc::HardLine);
docs.push(text(kw));
} else if cuddle {
docs.push(text(format!(" {kw}")));
} else {
docs.push(Doc::HardLine);
docs.push(text(kw));
}
}
pub(super) fn if_stmt(&self, parts: &IfParts<'_>) -> Doc {
let mut head = Vec::new();
if let Some(q) = qualifier {
if let Some(q) = parts.qualifier {
head.push(text(format!("{q} ")));
}
self.word_then("if", after_kw, &mut head);
let (parens, taken) = self.header_parens(cond, &then.meta);
self.word_then("if", parts.after_kw, &mut head);
let (parens, taken) = self.header_parens(parts.cond, &parts.then.meta);
head.push(parens);
let prefix = concat(head);
// A line comment trailing the then-branch runs to end of line, so a
// cuddled `else` would be swallowed into its text.
let then_is_block =
matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta);
let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)];
if let Some(els) = els {
// A comment written before `else` prints before it, each on its
// own line: it is where the source put it, and after the keyword
// it would have crossed a token.
if !else_comments.is_empty() {
docs.push(Doc::HardLine);
for c in else_comments {
docs.push(self.comment(c));
docs.push(Doc::HardLine);
}
docs.push(text("else"));
} else if then_is_block && self.else_cuddles(ends_labelled(then)) {
docs.push(text(" else"));
} else {
docs.push(Doc::HardLine);
docs.push(text("else"));
}
let then_is_block = matches!(parts.then.kind, StmtKind::Block { .. })
&& !trailing_ends_line(&parts.then.meta);
let mut docs = vec![self.stmt_as_body_from(prefix, parts.then, taken)];
if let Some(els) = parts.els {
let cuddle = then_is_block && self.else_cuddles(ends_labelled(parts.then));
self.push_else_keyword(
&mut docs,
cuddle,
parts.else_directives,
parts.else_comments,
"else",
);
// `else if` chains stay flat.
if let StmtKind::If {
qualifier: eq,
after_kw: ea,
cond: ec,
then: et,
else_comments: ecm,
els: ee,
qualifier,
after_kw,
cond,
then,
else_directives,
else_comments,
els: next_els,
} = &els.kind
{
docs.push(text(" "));
let mut meta_docs = self.leading(&els.meta);
docs.append(&mut meta_docs);
docs.push(self.if_stmt(eq, ea, ec, et, ecm, ee));
docs.push(self.if_stmt(&IfParts {
qualifier,
after_kw,
cond,
then,
else_directives,
else_comments,
els: next_els,
}));
docs.extend(self.trailing(&els.meta));
} else {
docs.push(self.stmt_as_body(text(""), els));
@@ -97,30 +132,21 @@ impl<'a> Fmt<'a> {
pub(super) fn gen_if(&self, g: &GenIf, depth: usize) -> Doc {
let mut docs = vec![text("if "), self.parens(&g.cond)];
let begin = self.cfg.style.begin;
let mut cuddle = self.gen_block(&mut docs, &g.then, depth, begin)
&& self.else_cuddles(g.then.end_label.is_some());
let (mut cuddle, mut dirs, mut cmts) = self.gen_then_branch(&mut docs, g, depth, begin);
let mut els = &g.els;
while let Some(e) = els {
match e.as_ref() {
GenElse::If(_meta, gi) => {
if cuddle {
docs.push(text(" else if "));
} else {
docs.push(Doc::HardLine);
docs.push(text("else if "));
}
self.push_else_keyword(&mut docs, cuddle, dirs, cmts, "else if ");
docs.push(self.parens(&gi.cond));
cuddle = self.gen_block(&mut docs, &gi.then, depth, begin)
&& self.else_cuddles(gi.then.end_label.is_some());
let next = self.gen_then_branch(&mut docs, gi, depth, begin);
cuddle = next.0;
dirs = next.1;
cmts = next.2;
els = &gi.els;
}
GenElse::Block(b) => {
if cuddle {
docs.push(text(" else"));
} else {
docs.push(Doc::HardLine);
docs.push(text("else"));
}
self.push_else_keyword(&mut docs, cuddle, dirs, cmts, "else");
self.gen_block(&mut docs, b, depth, begin);
break;
}
@@ -128,6 +154,26 @@ impl<'a> Fmt<'a> {
}
concat(docs)
}
fn gen_then_branch<'g>(
&self,
docs: &mut Vec<Doc>,
g: &'g GenIf,
depth: usize,
begin: Placement,
) -> (bool, &'g [ListDirective], &'g [Comment]) {
let is_block = self.gen_block(docs, &g.then, depth, begin);
if let Some(tr) = &g.then_trailing {
docs.push(text(" "));
docs.push(self.comment(tr));
}
let ends_line = g
.then_trailing
.as_ref()
.is_some_and(|c| is_line_comment(&c.text) || !c.text.trim_end().ends_with("*/"));
let cuddle = is_block && !ends_line && self.else_cuddles(g.then.end_label.is_some());
(cuddle, &g.else_directives, &g.else_comments)
}
}
/// Whether a statement is a block closed by `end : label`.
+19 -17
View File
@@ -147,26 +147,28 @@ impl<'a> Fmt<'a> {
ListItem::from_meta(&d.meta, concat(docs))
})
.collect();
if items.len() == 1 {
let item = items.into_iter().next().unwrap();
let mut docs = self.leading(&Meta { leading: item.leading, ..Meta::default() });
docs.push(item.doc);
let mut ends_line = self.inline_comments(&item.before_sep, &mut docs);
if let Some(tr) = item.trailing {
docs.push(if ends_line { Doc::HardLine } else { text(" ") });
docs.push(self.comment(&tr));
ends_line = is_line_comment(&tr.text);
let items = match <[ListItem; 1]>::try_from(items) {
Ok([item]) => {
let mut docs = self.leading(&Meta { leading: item.leading, ..Meta::default() });
docs.push(item.doc);
let mut ends_line = self.inline_comments(&item.before_sep, &mut docs);
if let Some(tr) = item.trailing {
docs.push(if ends_line { Doc::HardLine } else { text(" ") });
docs.push(self.comment(&tr));
ends_line = is_line_comment(&tr.text);
}
// The caller appends the `;`; a line comment runs to end of line,
// so it has to go on the next one.
if ends_line {
docs.push(Doc::HardLine);
}
return concat(docs);
}
// The caller appends the `;`; a line comment runs to end of line,
// so it has to go on the next one.
if ends_line {
docs.push(Doc::HardLine);
}
return concat(docs);
}
Err(items) => items,
};
// Multiple declarators: allow one-per-line continuation.
let mut inner = Vec::new();
let last = items.len() - 1;
let last = items.len().saturating_sub(1);
for (i, item) in items.into_iter().enumerate() {
let meta = Meta { leading: item.leading, ..Meta::default() };
inner.extend(self.leading(&meta));
+9 -2
View File
@@ -55,13 +55,20 @@ impl<'a> Fmt<'a> {
}
docs.push(self.instance(only, depth));
} else {
if !on_fresh_line {
let one_per_line = self.cfg.style.port_lists == crate::style::PortLists::OnePerLine;
if !one_per_line && !on_fresh_line {
docs.push(text(" "));
}
// Several instances share one declaration: keep them on one line
// if they fit, otherwise one per line, indented under the head.
let last = inst.instances.len() - 1;
// Under `OnePerLine`, start inside the indented group so when the
// list breaks every instance — first and rest alike — opens and
// closes at the same indented column.
let last = inst.instances.len().saturating_sub(1);
let mut inner = Vec::new();
if one_per_line && !on_fresh_line {
inner.push(Doc::Line);
}
for (i, instance) in inst.instances.iter().enumerate() {
inner.extend(self.leading(&instance.meta));
inner.push(self.instance(instance, depth + 1));
+33 -31
View File
@@ -429,43 +429,45 @@ impl<'a> Fmt<'a> {
item
})
.collect();
if items.len() == 1 {
let item = items.into_iter().next().unwrap();
docs.push(item.doc);
// The last pair's separator is the `;`, so its `before_sep`
// comments print in front of it.
if self.inline_comments(&item.before_sep, &mut docs) {
docs.push(Doc::HardLine);
}
docs.push(text(";"));
if let Some(tr) = item.trailing {
docs.push(text(" "));
docs.push(self.comment(&tr));
}
} else {
let last = items.len() - 1;
let mut inner = Vec::new();
for (i, item) in items.into_iter().enumerate() {
inner.push(item.doc);
if self.inline_comments(&item.before_sep, &mut inner) {
inner.push(Doc::HardLine);
}
if i < last {
inner.push(text(","));
} else {
inner.push(text(";"));
match <[ListItem; 1]>::try_from(items) {
Ok([item]) => {
docs.push(item.doc);
// The last pair's separator is the `;`, so its `before_sep`
// comments print in front of it.
if self.inline_comments(&item.before_sep, &mut docs) {
docs.push(Doc::HardLine);
}
docs.push(text(";"));
if let Some(tr) = item.trailing {
inner.push(text(" "));
inner.push(self.comment(&tr));
if i < last {
docs.push(text(" "));
docs.push(self.comment(&tr));
}
}
Err(items) => {
let last = items.len().saturating_sub(1);
let mut inner = Vec::new();
for (i, item) in items.into_iter().enumerate() {
inner.push(item.doc);
if self.inline_comments(&item.before_sep, &mut inner) {
inner.push(Doc::HardLine);
}
} else if i < last {
inner.push(Doc::Line);
if i < last {
inner.push(text(","));
} else {
inner.push(text(";"));
}
if let Some(tr) = item.trailing {
inner.push(text(" "));
inner.push(self.comment(&tr));
if i < last {
inner.push(Doc::HardLine);
}
} else if i < last {
inner.push(Doc::Line);
}
}
docs.push(group(vec![indent(inner)]));
}
docs.push(group(vec![indent(inner)]));
}
concat(docs)
}
+90 -21
View File
@@ -37,7 +37,10 @@ use crate::fence::{self, Region};
use crate::printer::Printer;
use crate::range::{self, Split};
use crate::style::{Style, LUCISV};
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
use crate::verify::{
stream_from_tokens, verify_convergence, verify_equivalence_items, Item as VerifyItem,
VerificationError,
};
use vlog_parser::ast::*;
/// Everything a formatting run is configured with.
@@ -159,15 +162,64 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
format_styled(source, config)
}
/// Lexed/parsed input alongside its collected fenced regions and flattened
/// verification stream, built once per formatting request.
pub(crate) struct ParsedSource {
pub(crate) file: SourceFile,
pub(crate) regions: Vec<Region>,
pub(crate) items: Vec<VerifyItem>,
}
/// Lex and parse `source` once, also collecting fenced regions and the
/// flattened token stream used for safety-net verification.
pub(crate) fn parse_once(source: &str) -> Result<ParsedSource, vlog_parser::Error> {
let tokens = vlog_parser::tokenize(source).map_err(vlog_parser::Error::Lex)?;
let items = stream_from_tokens(&tokens);
let file = vlog_parser::parse(tokens, source).map_err(vlog_parser::Error::Parse)?;
let regions = fence::collect(source, &file);
Ok(ParsedSource { file, regions, items })
}
/// [`format_source`] under exactly `config`'s style, `auto_style` ignored.
pub(crate) fn format_styled(source: &str, config: &Config) -> Result<String, FormatError> {
let output = format_once(source, config).map_err(FormatError::Source)?;
verify_equivalence(source, &output)?;
let again = format_once(&output, config).map_err(VerificationError::Reparse)?;
verify_convergence(&output, &again)?;
let parsed = parse_once(source).map_err(FormatError::Source)?;
let output = render_parsed(source, &parsed.file, &parsed.regions, config);
if output != source {
verify_rendered(source, &parsed.items, &output, config)?;
}
Ok(output)
}
/// Verify a rendered whole-file `output` against `before_items` and a single
/// re-parse/re-render convergence pass, returning the parsed output tree and
/// fence regions for reuse (e.g. `auto::canonical`).
pub(crate) fn verify_rendered(
_source: &str,
before_items: &[VerifyItem],
output: &str,
config: &Config,
) -> Result<(SourceFile, Vec<Region>), FormatError> {
verify_equivalence_items(before_items, output)?;
let out_tokens = vlog_parser::tokenize(output)
.map_err(|e| VerificationError::Reparse(vlog_parser::Error::Lex(e)))?;
let out_file = vlog_parser::parse(out_tokens, output)
.map_err(|e| VerificationError::Reparse(vlog_parser::Error::Parse(e)))?;
let out_regions = fence::collect(output, &out_file);
let again = render_parsed(output, &out_file, &out_regions, config);
verify_convergence(output, &again)?;
Ok((out_file, out_regions))
}
/// Render an already-parsed `(file, regions)` under `config`.
pub(crate) fn render_parsed(
source: &str,
file: &SourceFile,
regions: &[Region],
config: &Config,
) -> String {
render(&Fmt { cfg: config, src: source, regions, splits: &[] }, file, config)
}
/// Format only the constructs intersecting `lines`, emitting every other byte
/// exactly as it was written.
///
@@ -187,11 +239,26 @@ pub fn format_range(
config: &Config,
lines: &range::LineRanges,
) -> Result<String, FormatError> {
let config = &crate::auto::concrete(source, config);
let file = vlog_parser::parse_source(source).map_err(FormatError::Source)?;
let selection = range::select(source, &file, lines);
let output = format_selected(source, config, &selection).map_err(FormatError::Source)?;
verify_equivalence(source, &output)?;
let (resolved, cached) = crate::auto::resolve_concrete(source, config);
let parsed = match cached {
Some(p) => p,
None => parse_once(source).map_err(FormatError::Source)?,
};
format_range_with_parsed(source, &resolved, lines, &parsed)
}
pub(crate) fn format_range_with_parsed(
source: &str,
config: &Config,
lines: &range::LineRanges,
parsed: &ParsedSource,
) -> Result<String, FormatError> {
let selection = range::select(source, &parsed.file, lines);
let output = format_selected_parsed(source, &parsed.file, config, &selection);
if output == source {
return Ok(output);
}
verify_equivalence_items(&parsed.items, &output)?;
let again = format_selected(&output, config, &selection).map_err(VerificationError::Reparse)?;
verify_convergence(&output, &again)?;
Ok(output)
@@ -218,7 +285,7 @@ pub(crate) fn print_run(
base: &str,
) -> String {
let regions = fence::collect(source, file);
let fmt = Fmt { cfg: config, src: source, regions, splits: Vec::new() };
let fmt = Fmt { cfg: config, src: source, regions: &regions, splits: &[] };
let docs = match run {
Run::Items(items, depth) => fmt.item_seq(items, depth),
Run::Stmts(stmts) => fmt.stmt_seq(stmts),
@@ -232,11 +299,15 @@ pub(crate) fn print_run(
out
}
/// A single unverified formatting pass: parse, lay out, print.
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
let file = vlog_parser::parse_source(source)?;
let regions = fence::collect(source, &file);
Ok(render(&Fmt { cfg: config, src: source, regions, splits: Vec::new() }, &file, config))
fn format_selected_parsed(
source: &str,
file: &SourceFile,
config: &Config,
selection: &range::Selection,
) -> String {
let plan = range::plan(source, file, selection);
let fmt = Fmt { cfg: config, src: source, regions: &plan.regions, splits: &plan.splits };
render(&fmt, file, config)
}
/// The same pass, restricted to the units `selection` picked out.
@@ -246,9 +317,7 @@ fn format_selected(
selection: &range::Selection,
) -> Result<String, vlog_parser::Error> {
let file = vlog_parser::parse_source(source)?;
let plan = range::plan(source, &file, selection);
let fmt = Fmt { cfg: config, src: source, regions: plan.regions, splits: plan.splits };
Ok(render(&fmt, &file, config))
Ok(format_selected_parsed(source, &file, config, selection))
}
/// Lay the file out and print it, ending in exactly one newline.
@@ -271,10 +340,10 @@ struct Fmt<'a> {
src: &'a str,
/// The byte ranges of `src` emitted exactly as written, sorted and
/// non-overlapping: fenced regions, plus whatever a range run left alone.
regions: Vec<Region>,
regions: &'a [Region],
/// Scope-bearing items a range run descends into. Empty for a whole-file
/// run.
splits: Vec<Split>,
splits: &'a [Split],
}
/// A name, plus the space that terminates it when it is an escaped identifier.
+40 -12
View File
@@ -100,12 +100,7 @@ impl<'a> Fmt<'a> {
ports
.iter()
.zip(&aligns)
.map(|(p, a)| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
})
})
.map(|(p, a)| self.list_elem(p, |p| self.ansi_port_item(p, a.as_ref())))
.collect()
}
PortList::NonAnsi(ports) => ports
@@ -159,6 +154,16 @@ impl<'a> Fmt<'a> {
concat(docs)
}
fn ansi_port_item(&self, p: &AnsiPort, align: Option<&Align>) -> ListItem {
if p.meta.attrs.is_empty() {
return ListItem::from_meta(&p.meta, self.ansi_port(p, align)).with_comma(p.comma);
}
let first_attr = p.meta.attrs[0].span.start;
let mut item = ListItem::from_meta(&p.meta, self.ansi_port_plain(p)).with_comma(p.comma);
item.leading.retain(|c| c.span.start < first_attr);
item
}
fn ansi_port(&self, p: &AnsiPort, align: Option<&Align>) -> Doc {
align::render(&self.ansi_port_cells(p), ANSI_PORT_COLS, align)
}
@@ -168,10 +173,9 @@ impl<'a> Fmt<'a> {
/// port with no prefix at all (a continuation port, `output a, b`) is one
/// cell, which is what takes it out of every alignment group.
fn ansi_port_cells(&self, p: &AnsiPort) -> Vec<Doc> {
// A comment in one of the port's own gaps makes the row a width no
// other row shares, so it is one cell and joins no alignment group —
// the rule an attributed connection already follows.
if !p.after_dir.is_empty() || !p.before_name.is_empty() {
// Attributes or comments in the port's own gaps make the row a width
// no other row shares, so it is one cell and joins no alignment group.
if !p.meta.attrs.is_empty() || !p.after_dir.is_empty() || !p.before_name.is_empty() {
return vec![self.ansi_port_plain(p)];
}
let mut prefix = Vec::new();
@@ -203,10 +207,34 @@ impl<'a> Fmt<'a> {
vec![concat(prefix), concat(docs)]
}
/// An ANSI port written out in one piece, for the rows that carry a
/// comment in one of their own gaps and so cannot be aligned.
/// An ANSI port written out in one piece, for the rows that carry
/// attributes or a comment in one of their own gaps and so cannot be aligned.
fn ansi_port_plain(&self, p: &AnsiPort) -> Doc {
let mut docs = Vec::new();
if let Some(first) = p.meta.attrs.first() {
let mut after =
p.meta.leading.iter().filter(|c| c.span.start >= first.span.start).peekable();
for attr in &p.meta.attrs {
while let Some(c) = after.next_if(|c| c.span.start < attr.span.start) {
docs.push(self.comment(c));
docs.push(if super::comment::is_line_comment(&c.text) {
Doc::HardLine
} else {
text(" ")
});
}
docs.push(self.raw_inline(attr));
docs.push(text(" "));
}
for c in after {
docs.push(self.comment(c));
docs.push(if super::comment::is_line_comment(&c.text) {
Doc::HardLine
} else {
text(" ")
});
}
}
if let Some(dir) = &p.dir {
self.word_then(dir, &p.after_dir, &mut docs);
}
+17 -3
View File
@@ -296,9 +296,23 @@ impl<'a> Fmt<'a> {
docs.push(self.closing_labeled(join_kw, end_label, end_label_comments));
concat(docs)
}
StmtKind::If { qualifier, after_kw, cond, then, else_comments, els } => {
self.if_stmt(qualifier, after_kw, cond, then, else_comments, els)
}
StmtKind::If {
qualifier,
after_kw,
cond,
then,
else_directives,
else_comments,
els,
} => self.if_stmt(&super::branch::IfParts {
qualifier,
after_kw,
cond,
then,
else_directives,
else_comments,
els,
}),
StmtKind::Case { qualifier, kw, after_kw, expr, inside, items, dangling } => {
let mut docs = Vec::new();
if let Some(q) = qualifier {
+3 -3
View File
@@ -31,7 +31,7 @@ pub(super) enum Slot<'r> {
impl<'a> Fmt<'a> {
/// What to do with one comment, given the fenced regions of the source.
pub(super) fn slot(&self, c: &Comment) -> Slot<'_> {
match fence::region_at(&self.regions, c.span.start as usize) {
match fence::region_at(self.regions, c.span.start as usize) {
None => Slot::Normal,
Some(r) if r.fence == c.span.start as usize => Slot::Opens(r),
Some(_) => Slot::Covered,
@@ -41,7 +41,7 @@ impl<'a> Fmt<'a> {
/// True if this node's code is inside a verbatim region, i.e. its bytes
/// are already being emitted as written and it must not be laid out.
pub(super) fn is_verbatim(&self, span: TextRange) -> bool {
fence::region_at(&self.regions, span.start as usize).is_some()
fence::region_at(self.regions, span.start as usize).is_some()
}
/// The verbatim region this byte offset *opens*, if it opens one.
@@ -50,7 +50,7 @@ impl<'a> Fmt<'a> {
/// fence comment, the first leading comment of a run's first item, or —
/// when that item has no leading comments — the item's own code.
pub(super) fn opens_at(&self, at: usize) -> Option<&Region> {
fence::region_at(&self.regions, at).filter(|r| r.fence == at)
fence::region_at(self.regions, at).filter(|r| r.fence == at)
}
/// The split recorded for the item starting at this byte offset.
+33 -9
View File
@@ -21,9 +21,9 @@ mod locate;
mod scope;
use crate::fence;
use crate::format::{format_range, print_run, Config, FormatError};
use crate::format::{format_range, format_range_with_parsed, print_run, Config, FormatError};
use crate::range::LineRanges;
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
use crate::verify::{verify_convergence, verify_equivalence_items, VerificationError};
use locate::{any_error, resolve, Found, Locator, Target};
use scope::Scope;
use vlog_parser::ast::SourceFile;
@@ -47,14 +47,35 @@ pub fn format_selection(
config: &Config,
lines: &LineRanges,
) -> Result<String, FormatError> {
let config = &crate::auto::concrete(source, config);
let tree = Tree::parse(source).map_err(FormatError::Source)?;
let Some(root) = Scope::root(&tree.file) else {
return format_range(source, config, lines);
let (config, cached) = crate::auto::resolve_concrete(source, config);
let config = &config;
let (tree, regions, before_items) = match cached {
Some(p) => (Tree { file: p.file, diagnostics: Vec::new() }, Some(p.regions), Some(p.items)),
None => (Tree::parse(source).map_err(FormatError::Source)?, None, None),
};
let locator = Locator::new(source, fence::collect(source, &tree.file));
let Some(root) = Scope::root(&tree.file) else {
return match (regions, before_items) {
(Some(regions), Some(items)) => format_range_with_parsed(
source,
config,
lines,
&crate::format::ParsedSource { file: tree.file, regions, items },
),
_ => format_range(source, config, lines),
};
};
let regions = regions.unwrap_or_else(|| fence::collect(source, &tree.file));
let locator = Locator::new(source, regions.clone());
let Ok(targets) = select(&locator, root, source, lines) else {
return format_range(source, config, lines);
return match before_items {
Some(items) => format_range_with_parsed(
source,
config,
lines,
&crate::format::ParsedSource { file: tree.file, regions, items },
),
None => format_range(source, config, lines),
};
};
if targets.is_empty() {
return Ok(source.to_string());
@@ -62,7 +83,10 @@ pub fn format_selection(
tree.check_clear(source, root, &targets)?;
let output = splice(source, &tree.file, root, config, &targets)
.ok_or_else(|| lost("the selection could not be cut out of its lines"))?;
verify_equivalence(source, &output)?;
match before_items {
Some(items) => verify_equivalence_items(&items, &output)?,
None => crate::verify::verify_equivalence(source, &output)?,
}
let again = replay(&output, config, &targets)?;
verify_convergence(&output, &again)?;
Ok(output)
+17 -3
View File
@@ -145,6 +145,15 @@ impl std::error::Error for VerificationError {}
/// and the same comments, in the same order, ignoring whitespace.
pub fn verify_equivalence(input: &str, output: &str) -> Result<(), VerificationError> {
let before = lex_stream(input, Side::Input)?;
verify_equivalence_items(&before, output)
}
/// Verify that `output` is lexically equivalent to an already-flattened input
/// token stream.
pub(crate) fn verify_equivalence_items(
before: &[Item],
output: &str,
) -> Result<(), VerificationError> {
let after = lex_stream(output, Side::Output)?;
for index in 0..before.len().max(after.len()) {
let expected = before.get(index);
@@ -173,8 +182,13 @@ pub fn verify_convergence(first: &str, second: &str) -> Result<(), VerificationE
/// Flatten `source` into tokens and comments, dropping all whitespace.
fn lex_stream(source: &str, side: Side) -> Result<Vec<Item>, VerificationError> {
let tokens = tokenize(source).map_err(|error| VerificationError::Lex { side, error })?;
let mut items = Vec::new();
for token in &tokens {
Ok(stream_from_tokens(&tokens))
}
/// Flatten pre-lexed `tokens` into the whitespace-free comparison stream.
pub(crate) fn stream_from_tokens(tokens: &[vlog_parser::token::Token]) -> Vec<Item> {
let mut items = Vec::with_capacity(tokens.len());
for token in tokens {
for comment in &token.leading {
items.push(comment_item(&comment.text, comment.line, comment.col));
}
@@ -193,7 +207,7 @@ fn lex_stream(source: &str, side: Side) -> Result<Vec<Item>, VerificationError>
}
}
collapse_implicit_sensitivity(&mut items);
Ok(items)
items
}
/// Rewrite `@ ( * )` to `@ *` so the two spellings of an implicit sensitivity
+385
View File
@@ -0,0 +1,385 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Round 5B formatter regression suite: `#44` generate `end`/`else` comments,
//! `#45` `` `ifdef `` between `end` and `else`, `#46` ANSI port attributes,
//! `#47` multi-instance declarations under one-per-line styles, and parse-once
//! `--style auto` invariants.
use vlog_formatter::style::{self, PRESETS};
use vlog_formatter::{
format_auto, format_range, format_selection, format_source, resolve_style, verify_equivalence,
Config, LineRanges,
};
fn auto_cfg() -> Config {
Config::named("auto").expect("auto is a style")
}
fn check_all_presets(src: &str) {
for &preset in &PRESETS {
let cfg = Config::styled(preset);
let out = format_source(src, &cfg)
.unwrap_or_else(|e| panic!("failed under `{}`:\n{src}\nerr: {e}", preset.name));
verify_equivalence(src, &out)
.unwrap_or_else(|e| panic!("equivalence failed under `{}`: {e}", preset.name));
let again = format_source(&out, &cfg).expect("idempotent");
assert_eq!(again, out, "not idempotent under `{}`", preset.name);
}
let cfg = auto_cfg();
let (out, chosen) = format_auto(src, &cfg).expect("auto formats");
let (again, chosen2) = format_auto(&out, &cfg).expect("auto idempotent");
assert_eq!(
again, out,
"auto not idempotent (first `{}` -> second `{}`)",
chosen.name, chosen2.name
);
let r1 = resolve_style(&out, &cfg).style.name;
let r2 = resolve_style(&again, &cfg).style.name;
assert_eq!(r1, r2, "resolve_style changed name on second pass");
}
// ----------------------------------------------------------------------
// #44 — comments between generate `end` / `end : label` and `else`
// ----------------------------------------------------------------------
#[test]
fn generate_end_else_comments_format_cleanly_under_every_style() {
let cases = [
"\
module m;
if (A) begin
wire x = 1;
end
// comment between end and else
else begin
wire x = 2;
end
endmodule
",
"\
module m;
if (A) begin : gen_a
wire x = 1;
end : gen_a // trailing comment on labelled end
else if (B) begin : gen_b
wire x = 2;
end : gen_b /* block */ // trailing line
// comment before final else
else begin : gen_c
wire x = 3;
end : gen_c
endmodule
",
"\
module m;
if (A) begin : g
wire x = 1;
end : g /* mid */ else begin : h
wire x = 2;
end : h
endmodule
",
];
for src in cases {
check_all_presets(src);
}
}
// ----------------------------------------------------------------------
// #45 — `` `ifdef `` and conditional directives between `end` and `else`
// ----------------------------------------------------------------------
#[test]
fn ifdef_between_end_and_else_formats_cleanly_under_every_style() {
let cases = [
// Balanced directives between `end` and `else` (generate).
"\
module m;
if (A) begin : g1
wire w = 1;
end : g1 // end g1
`ifdef FOO // check
`endif
// before else
else begin : g2
wire w = 2;
end : g2
endmodule
",
// Balanced directives between `end` and `else` (procedural).
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef BAR
`define BAZ 1
`endif
else begin
x = 2;
end
end
endmodule
",
// Conditional `else` inside `` `ifdef `` (procedural + generate + trailing else).
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef FOO
else begin
x = 2;
end
`endif
end
if (A) begin : g1
wire y = 1;
end : g1
`ifdef FOO
else if (B) begin : g2
wire y = 2;
end : g2
`else
else begin : g3
wire y = 3;
end : g3
`endif
endmodule
",
"\
module m;
always_comb
if (a) begin
x = 1;
end
`ifdef FOO
else if (b) begin
x = 2;
end
`endif
else begin
x = 3;
end
endmodule
",
// Unconditional `else if ... else ...` chain after conditional `` `ifdef ... `endif ``.
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef FOO
else if (b) begin
x = 2;
end
`endif
else if (c) begin
x = 3;
end else begin
x = 4;
end
end
if (A) begin : g1
wire w = 1;
end : g1
`ifdef FOO
else if (B) begin : g2
wire w = 2;
end : g2
`endif
else if (C) begin : g3
wire w = 3;
end : g3 else begin : g4
wire w = 4;
end : g4
endmodule
",
// Nested `` `ifdef ... `endif `` inside shared `else` tail after `` `else ... `endif ``.
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef FOO
else if (b) begin
x = 2;
`else
else if (c) begin
x = 3;
`endif
`ifdef INNER
x = 4;
`else
x = 5;
`endif
end
end
if (A) begin : g1
wire w = 1;
end : g1
`ifdef FOO
else if (B) begin : g2
wire w = 2;
`else
else if (C) begin : g2
wire w = 3;
`endif
`ifdef INNER
wire z = 1;
`endif
end : g2
endmodule
",
];
for src in cases {
check_all_presets(src);
}
}
// ----------------------------------------------------------------------
// #46 — attributes on ANSI ports
// ----------------------------------------------------------------------
#[test]
fn ansi_port_attributes_format_cleanly_under_every_style() {
let cases = [
"\
module m (
(* keep *) input logic a,
output logic b
);
endmodule
",
"\
module m (
// doc before
(* keep *) (* async_reg *) // comment after attr
input logic [7:0] a,
(* mark_debug = \"true\" *) pkg::word_t b,
(* keep *) bus_if.slave bus,
output logic [7:0] c,
output logic d
);
endmodule
",
];
for src in cases {
check_all_presets(src);
}
let simple = "module m ((* keep *) input logic a, output logic b);\nendmodule\n";
let g_out = format_source(simple, &Config::styled(style::GOOGLE)).expect("google");
assert_eq!(
g_out,
"module m (\n (* keep *) input logic a,\n output logic b\n);\nendmodule\n"
);
}
// ----------------------------------------------------------------------
// #47 — multi-instance declarations honor one-per-line styles
// ----------------------------------------------------------------------
#[test]
fn multi_instance_honors_one_per_line_and_keeps_fit_layout() {
let src = "module m;\n p1 u8 (.a(a)), u9 (.a(b));\nendmodule\n";
check_all_presets(src);
// Under OnePerLine styles, each instance opens and closes at the same
// indented level under the module type (no asymmetric hanging layout).
assert_eq!(
format_source(src, &Config::styled(style::GOOGLE)).expect("google"),
"module m;\n p1\n u8 (\n .a(a)\n ),\n u9 (\n .a(b)\n );\nendmodule\n"
);
assert_eq!(
format_source(src, &Config::styled(style::LOWRISC)).expect("lowrisc"),
"module m;\n p1\n u8 (\n .a(a)\n ),\n u9 (\n .a(b)\n );\nendmodule\n"
);
assert_eq!(
format_source(src, &Config::styled(style::MICROSOFT)).expect("microsoft"),
"module m;\n p1\n u8 (\n .a(a)\n ),\n u9 (\n .a(b)\n );\nendmodule\n"
);
assert_eq!(
format_source(src, &Config::styled(style::NXP)).expect("nxp"),
"module m;\n p1\n u8 (\n .a(a)\n ),\n u9 (\n .a(b)\n );\nendmodule\n"
);
// Fit styles preserve their existing single-line / hanging fit behavior.
assert_eq!(
format_source(src, &Config::styled(style::LUCISV)).expect("lucisv"),
"module m;\n p1 u8 (.a(a)), u9 (.a(b));\nendmodule\n"
);
// Parameter overrides + aligned multi-port connections + ordered/empty.
check_all_presets(
"module m;\n p1 #(.W(8), .D(16)) u8 (.clk(clk), .data_o(d8)), u9 (.clk(clk), .data_o(d9));\n p2 u0 (), u1 ();\n p3 u2 (a), u3 (b);\nendmodule\n",
);
}
// ----------------------------------------------------------------------
// Parse-once --style auto & unwrap-free single-element paths
// ----------------------------------------------------------------------
#[test]
fn parse_once_auto_matches_every_preset_and_ranges() {
let sample = "\
module m (
input logic clk,
input logic rst_n,
output logic q
);
always_ff @(posedge clk) begin : blk
if (!rst_n) begin : r
q <= 1'b0;
end : r else begin : w
q <= 1'b1;
end : w
end : blk
endmodule
";
let cfg = auto_cfg();
for &preset in &PRESETS {
let formatted = format_source(sample, &Config::styled(preset)).expect("preset formats");
let matching_auto =
Config { indent_width: preset.indent, max_width: preset.line_length, ..cfg.clone() };
let (auto_out, picked) = format_auto(&formatted, &matching_auto).expect("auto formats");
assert_eq!(auto_out, formatted, "already formatted under `{}`", preset.name);
// `picked` leaves `formatted` untouched, and `resolve_style` picks the
// earliest preset in PRESETS that also leaves it untouched.
let picked_cfg = Config { style: picked, auto_style: false, ..matching_auto.clone() };
assert_eq!(format_source(&formatted, &picked_cfg).expect("picked fixes"), formatted);
let resolved = resolve_style(&formatted, &matching_auto);
assert_eq!(format_source(&formatted, &resolved).expect("resolved fixes"), formatted);
assert_eq!(resolve_style(&auto_out, &matching_auto).style.name, resolved.style.name);
}
// Parse error fallback under auto stays well-behaved across entry points.
let broken = "module m;\n assign x = ;\nendmodule\n";
assert!(format_source(broken, &cfg).is_err());
assert!(format_auto(broken, &cfg).is_err());
assert_eq!(resolve_style(broken, &cfg).style, style::LUCISV);
// Range & selection formatting under auto.
let g_src = format_source(
"module m;\n always_comb begin\n if (a) begin x = 1; end else begin x = 2; end\n end\n wire z=1;\nendmodule\n",
&Config::styled(style::GOOGLE),
)
.expect("google");
let unfmt_tail = g_src.replace("wire z = 1;", "wire z=1;");
let lines = LineRanges::parse("9").expect("range");
let ranged = format_range(&unfmt_tail, &cfg, &lines).expect("range");
assert!(ranged.contains("wire z = 1;"), "{ranged}");
let selected = format_selection(&unfmt_tail, &cfg, &lines).expect("selection");
assert_eq!(selected, ranged);
// Single declarator & single continuous assign (formerly `.unwrap()` paths).
check_all_presets(
"module m;\n logic /* before_semi */ a /* semi */ ;\n assign /* b */ w = 1 /* s */ ;\nendmodule\n",
);
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+7
View File
@@ -441,6 +441,13 @@ pub struct GateInstance {
pub struct GenIf {
pub cond: Expr,
pub then: GenBlock,
/// Trailing comment written on `then`'s `end` / `end : label` line when an
/// `else` branch follows (keeping it out of `else`'s leading comments).
pub then_trailing: Option<Comment>,
/// Balanced/non-conditional directives between `then` and `else`.
pub else_directives: Vec<ListDirective>,
/// Comments between `then` (or its intervening directives) and `else`.
pub else_comments: Vec<Comment>,
pub els: Option<Box<GenElse>>,
/// Code extent of the whole `if`, its `else` branch included.
pub span: TextRange,
+2
View File
@@ -130,6 +130,8 @@ pub enum StmtKind {
after_kw: Vec<Comment>,
cond: Expr,
then: Box<Stmt>,
/// Balanced/non-conditional directives between `then` and `else`.
else_directives: Vec<ListDirective>,
/// Comments written between the then-branch and the `else` keyword.
/// They are kept here, not on `els`, because printing them after the
/// keyword moves them across it and the safety net rejects that.
+13
View File
@@ -256,6 +256,19 @@ impl<'a> Parser<'a> {
Meta { leading, blank_before, ..Meta::default() }
}
/// Consume any `(* ... *)` attributes at the cursor, preserving any
/// interleaved comments (trailing on the same line or leading the next
/// line) in `meta.leading` in source order.
pub(super) fn take_attrs(&mut self, meta: &mut Meta) {
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.take_raw_text());
meta.leading.append(&mut self.pending_trailing);
meta.leading.append(&mut self.pending_leading);
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
}
/// Harvest trailing comments accumulated since the last harvest.
///
/// Several comments merge into one, joined by a space, as they always
+4 -1
View File
@@ -171,7 +171,10 @@ impl<'a> Parser<'a> {
/// This is what keeps `x[i] = 1;` an assignment: what follows the
/// brackets there is `=`, not a name.
pub(super) fn at_typed_declarator(&self) -> bool {
let mut p = self.pos;
self.at_typed_declarator_at(self.pos)
}
pub(super) fn at_typed_declarator_at(&self, mut p: usize) -> bool {
while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) {
p += 2;
}
@@ -54,6 +54,13 @@ pub(super) struct Harvested {
pub(super) carried_comma: bool,
}
/// Comments and directives standing between `then` and `else`.
pub(super) struct ElseGap {
pub(super) then_trailing: Option<Comment>,
pub(super) directives: Vec<ListDirective>,
pub(super) comments: Vec<Comment>,
}
/// The three fragment shapes, in the order [`fragment_file`] tries them:
/// narrowest grammar first, so the shape that can only be one thing gets to
/// claim it before the shape that could read it as something else.
@@ -200,6 +207,77 @@ impl<'a> Parser<'a> {
found
}
/// True when directives (with balanced conditional nesting) stand between
/// the current position (`then` just finished) and a real `else` keyword.
pub(super) fn has_else_past_directives(&self) -> bool {
self.else_past_directives_at(self.pos).is_some()
}
/// Position of the `else` keyword reachable from `from` across only
/// balanced/non-conditional compiler directives, or `None`.
pub(super) fn else_past_directives_at(&self, from: usize) -> Option<usize> {
if !self.tokens.get(from).is_some_and(|t| t.kind == TokenKind::Directive) {
return None;
}
let mut i = from;
let mut depth = 0i32;
while let Some(t) = self.tokens.get(i) {
if t.kind == TokenKind::Eof {
return None;
}
if t.is_kw("else") && depth == 0 {
return Some(i);
}
if t.kind != TokenKind::Directive {
return None;
}
if opens_conditional(t) {
depth += 1;
} else if closes_conditional(t) {
depth -= 1;
if depth < 0 {
return None;
}
} else if continues_conditional(t) && depth == 0 {
return None;
}
i += 1;
}
None
}
/// Consume directives between `then` and `else`. Must only be called when
/// [`Parser::has_else_past_directives`] returned true.
pub(super) fn take_else_directives(&mut self) -> Vec<ListDirective> {
let mut dirs = Vec::new();
while !self.cur().is_kw("else") && !self.at_eof() {
let mut meta = self.take_meta();
let raw = self.take_raw_text();
meta.trailing = self.take_trailing();
dirs.push(ListDirective { raw, meta, before: 0, comma: false });
}
dirs
}
/// Leading/trailing artifacts separating an `if` branch's `then` from its
/// `else`.
pub(super) fn take_else_preamble(
&mut self,
capture_trailing: bool,
) -> PResult<Option<ElseGap>> {
let has_dirs = self.has_else_past_directives();
if !has_dirs && !self.cur().is_kw("else") {
if self.at_conditional_else_ahead() {
return self.error("conditional `else` after `if`");
}
return Ok(None);
}
let then_trailing = if capture_trailing { self.take_trailing() } else { None };
let directives = if has_dirs { self.take_else_directives() } else { Vec::new() };
let comments = self.take_dangling();
Ok(Some(ElseGap { then_trailing, directives, comments }))
}
/// True when the directive at the cursor continues or closes a conditional
/// region **this list did not open**, while a region opened at item scope
/// is still live.
+2 -6
View File
@@ -531,11 +531,7 @@ impl<'a> Parser<'a> {
// a port connection (IEEE 1800 §A.4.1.1), corpus
// `common_cells/src/cdc_fifo_gray.sv:140`. Harvested exactly the way
// an item's or a statement's attributes are.
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
self.take_attrs(&mut meta);
if self.eat_sym(".") {
let after_dot = self.take_gap();
let star = self.cur().span;
@@ -727,7 +723,7 @@ impl<'a> Parser<'a> {
self.expect_sym("(")?;
let mut args = Vec::new();
if !self.cur().is_sym(")") {
let first = self.parse_expr_item()?;
let first = self.parse_expr_item_with(true)?;
args = self.parse_expr_list(first, ")")?;
}
self.expect_sym(")")?;
+17 -10
View File
@@ -130,11 +130,7 @@ impl<'a> Parser<'a> {
// belongs inside the item's span.
let start = self.here();
let mut meta = self.take_meta();
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
self.take_attrs(&mut meta);
let mark =
ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() };
let kind = match self.parse_item_kind() {
@@ -603,19 +599,30 @@ impl<'a> Parser<'a> {
let cond = self.parse_expr()?;
self.expect_sym(")")?;
let then = self.parse_gen_block()?;
let els = if self.cur().is_kw("else") {
let meta = self.take_meta();
let (mut then_trailing, mut else_directives, mut else_comments) =
(None, Vec::new(), Vec::new());
let els = if let Some(gap) = self.take_else_preamble(then.is_block)? {
then_trailing = gap.then_trailing;
else_directives = gap.directives;
else_comments = gap.comments;
self.skip();
if self.cur().is_kw("if") {
Some(Box::new(GenElse::If(meta, Box::new(self.parse_gen_if()?))))
Some(Box::new(GenElse::If(Meta::default(), Box::new(self.parse_gen_if()?))))
} else {
let _ = meta;
Some(Box::new(GenElse::Block(self.parse_gen_block()?)))
}
} else {
None
};
Ok(GenIf { cond, then, els, span: self.span_from(start) })
Ok(GenIf {
cond,
then,
then_trailing,
else_directives,
else_comments,
els,
span: self.span_from(start),
})
}
fn parse_gen_for(&mut self) -> PResult<GenFor> {
+15 -6
View File
@@ -523,7 +523,11 @@ impl<'a> Parser<'a> {
return Ok((PortList::Empty, dangling, directives));
}
let ansi = {
let t = self.cur();
let mut p = self.pos;
while self.tokens.get(p).is_some_and(|t| t.kind == TokenKind::Attribute) {
p += 1;
}
let t = self.tokens.get(p).unwrap_or_else(|| self.cur());
t.is_kw("input")
|| t.is_kw("output")
|| t.is_kw("inout")
@@ -539,7 +543,7 @@ impl<'a> Parser<'a> {
// `#( ... )` override or packed dimensions) means a type and a
// name, while the `,` or `)` of `module m (a, b);` does not.
|| (t.kind == TokenKind::Ident
&& (self.at_typed_declarator() || self.at_modport_port()))
&& (self.at_typed_declarator_at(p) || self.at_modport_port_at(p)))
};
if ansi {
let mut ports = Vec::new();
@@ -620,6 +624,7 @@ impl<'a> Parser<'a> {
fn parse_ansi_port(&mut self) -> PResult<AnsiPort> {
let start = self.here();
let mut meta = self.take_meta();
self.take_attrs(&mut meta);
let dir = {
let t = self.cur();
if t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || t.is_kw("ref") {
@@ -671,10 +676,14 @@ impl<'a> Parser<'a> {
/// way — after an identifier anywhere else a `.` opens a member access —
/// so the shape is recognized here rather than in `parse_opt_data_type`.
pub(super) fn at_modport_port(&self) -> bool {
self.cur().kind == TokenKind::Ident
&& self.nth(1).is_sym(".")
&& self.nth(2).kind == TokenKind::Ident
&& self.nth(3).kind == TokenKind::Ident
self.at_modport_port_at(self.pos)
}
pub(super) fn at_modport_port_at(&self, p: usize) -> bool {
self.tokens.get(p).is_some_and(|t| t.kind == TokenKind::Ident)
&& self.tokens.get(p + 1).is_some_and(|t| t.is_sym("."))
&& self.tokens.get(p + 2).is_some_and(|t| t.kind == TokenKind::Ident)
&& self.tokens.get(p + 3).is_some_and(|t| t.kind == TokenKind::Ident)
}
/// The `bus_if.mp` of an interface port, as its type. The modport is glued
+11 -2
View File
@@ -318,7 +318,13 @@ impl<'a> Parser<'a> {
/// One element of a bracketed expression list, with the comments written
/// before it. The caller harvests the trailing comment after the comma.
/// Rejects omitted elements (`{d,, d}`, `{d,}`), except in call/argument
/// lists where [`Parser::parse_expr_item_with`] enables them.
pub(super) fn parse_expr_item(&mut self) -> PResult<ExprItem> {
self.parse_expr_item_with(false)
}
pub(super) fn parse_expr_item_with(&mut self, allow_omitted: bool) -> PResult<ExprItem> {
let start = self.here();
let meta = self.take_meta();
// Two element-only shapes no expression can start with: a named call
@@ -331,7 +337,7 @@ impl<'a> Parser<'a> {
self.parse_named_arg()?
} else if self.cur().is_sym("[") {
self.parse_value_range()?
} else if self.at_omitted_element() {
} else if allow_omitted && self.at_omitted_element() {
// An omitted positional argument: `create("asm_gen", , `gfn)`
// (`riscv_instr_base_test.sv:88`) takes the parameter's default
// (IEEE 1800 §13.5.3). It is an element with no tokens at all,
@@ -433,6 +439,7 @@ impl<'a> Parser<'a> {
first: ExprItem,
close: &str,
) -> PResult<Vec<ExprItem>> {
let allow_omitted = close == ")";
let mut items = vec![first];
loop {
if let Some(last) = items.last_mut() {
@@ -450,7 +457,9 @@ impl<'a> Parser<'a> {
}
return Ok(items);
}
items.push(self.parse_expr_item()?);
let after_named =
items.last().is_some_and(|i| matches!(i.expr.kind, ExprKind::NamedArg { .. }));
items.push(self.parse_expr_item_with(allow_omitted && !after_named)?);
}
}
@@ -296,7 +296,7 @@ impl<'a> Parser<'a> {
if has_parens {
self.skip();
if !self.cur().is_sym(")") {
let first = self.parse_expr_item()?;
let first = self.parse_expr_item_with(true)?;
args = self.parse_expr_list(first, ")")?;
}
self.expect_sym(")")?;
+246
View File
@@ -238,6 +238,11 @@ impl<'a> Parser<'a> {
mark: &ItemMark,
err: ParseError,
) -> PResult<ItemKind> {
if self.at_conditional_else_split(mark) {
if let Some(end_pos) = self.scan_if_conditional_else_extent(self.pos) {
return Ok(ItemKind::Verbatim(self.capture_split(mark, end_pos)));
}
}
if self.at_split_conditional(mark) {
if let Some((end_pos, conds_after)) =
self.scan_split_extent(mark, self.rival_end_kw(mark))
@@ -583,6 +588,247 @@ impl<'a> Parser<'a> {
after_kw
}
}
/// True when the cursor stands on an `` `ifdef `` / `` `ifndef `` whose
/// first non-directive token in an arm is `else`.
pub(super) fn at_conditional_else_ahead(&self) -> bool {
self.cond_else_at(self.pos)
}
fn cond_else_at(&self, pos: usize) -> bool {
if !self.tokens.get(pos).is_some_and(opens_conditional) {
return false;
}
let mut i = pos + 1;
let mut depth = 1i32;
while let Some(t) = self.tokens.get(i) {
if t.kind == TokenKind::Eof {
return false;
}
if t.kind == TokenKind::Directive {
if opens_conditional(t) {
depth += 1;
} else if closes_conditional(t) {
depth -= 1;
if depth == 0 {
return false;
}
}
i += 1;
continue;
}
return t.is_kw("else");
}
false
}
/// True when `mark` opened an `if` construct (with optional `unique`/
/// `priority` qualifier) and failed right at a conditional `` `else `` arm.
pub(super) fn at_conditional_else_split(&self, mark: &ItemMark) -> bool {
let head = self.tokens.get(mark.pos);
let starts_if = head.is_some_and(|t| t.is_kw("if"))
|| (head
.is_some_and(|t| t.is_kw("unique") || t.is_kw("unique0") || t.is_kw("priority"))
&& self.tokens.get(mark.pos + 1).is_some_and(|t| t.is_kw("if")));
starts_if && self.at_conditional_else_ahead()
}
/// Scan from an `` `ifdef `` directly following an `if`'s `then` branch
/// to one past the last token of its conditional-`else` / trailing `else`
/// chain, returning `None` if brackets, blocks, or `` `endif ``s do not
/// balance.
pub(super) fn scan_if_conditional_else_extent(&self, from: usize) -> Option<usize> {
let mut i = from;
loop {
if self.cond_else_at(i) {
i = self.scan_cond_else_region(i)?;
continue;
}
if let Some(else_pos) = self.else_past_directives_at(i) {
i = else_pos;
}
if self.tokens.get(i).is_some_and(|t| t.is_kw("else")) {
let (next, is_if) = self.scan_uncond_branch(i + 1)?;
i = next;
if is_if {
continue;
}
}
break;
}
Some(i)
}
fn scan_cond_else_region(&self, open_pos: usize) -> Option<usize> {
let mut cond = 1i32;
let mut outer_open = true;
let mut brackets = 0i32;
let mut blocks = 0i32;
let mut arm_started = false;
let mut i = open_pos + 1;
while let Some(t) = self.tokens.get(i) {
if t.kind == TokenKind::Eof {
return None;
}
if t.kind == TokenKind::Directive {
if opens_conditional(t) {
cond += 1;
} else if closes_conditional(t) {
cond -= 1;
if cond < 0 {
return None;
}
if outer_open && cond == 0 {
if brackets == 0 && blocks == 0 {
return Some(i + 1);
}
outer_open = false;
}
} else if continues_conditional(t) {
if outer_open && cond == 1 {
if arm_started {
i = self.skip_conditional_arms(i + 1)?;
if brackets == 0 && blocks == 0 {
return Some(i);
}
cond = 0;
outer_open = false;
continue;
}
} else if cond > 0 {
i = self.skip_conditional_arms(i + 1)?;
cond -= 1;
continue;
} else {
return None;
}
}
i += 1;
continue;
}
arm_started = true;
let prev = i.checked_sub(1).and_then(|p| self.tokens.get(p));
step_balance(&mut brackets, &mut blocks, prev, t)?;
if !outer_open && cond == 0 && brackets == 0 && blocks == 0 && ends_branch(t) {
return Some(self.close_token_end(i, t));
}
i += 1;
}
None
}
fn scan_uncond_branch(&self, from: usize) -> Option<(usize, bool)> {
let mut i = from;
let mut brackets = 0i32;
let mut blocks = 0i32;
let mut cond = 0i32;
let mut expect_if_cond = false;
let mut expect_body = true;
let mut is_if = false;
while let Some(t) = self.tokens.get(i) {
if t.kind == TokenKind::Eof {
return None;
}
if t.kind == TokenKind::Directive {
if opens_conditional(t) {
cond += 1;
} else if closes_conditional(t) {
cond -= 1;
if cond < 0 {
return None;
}
} else if continues_conditional(t) {
if cond == 0 {
return None;
}
i = self.skip_conditional_arms(i + 1)?;
cond -= 1;
continue;
}
i += 1;
continue;
}
if expect_body && brackets == 0 && blocks == 0 && cond == 0 {
if t.is_kw("unique") || t.is_kw("unique0") || t.is_kw("priority") {
i += 1;
continue;
}
if t.is_kw("if") {
expect_if_cond = true;
expect_body = false;
is_if = true;
i += 1;
continue;
}
expect_body = false;
}
let prev = i.checked_sub(1).and_then(|p| self.tokens.get(p));
step_balance(&mut brackets, &mut blocks, prev, t)?;
if expect_if_cond && brackets == 0 && t.is_sym(")") {
expect_if_cond = false;
expect_body = true;
i += 1;
continue;
}
if !expect_if_cond && cond == 0 && brackets == 0 && blocks == 0 && ends_branch(t) {
return Some((self.close_token_end(i, t), is_if));
}
i += 1;
}
None
}
fn close_token_end(&self, pos: usize, tok: &Token) -> usize {
if tok.is_sym(";") {
pos + 1
} else {
self.past_end_label(pos + 1)
}
}
}
fn step_balance(
brackets: &mut i32,
blocks: &mut i32,
prev: Option<&Token>,
t: &Token,
) -> Option<()> {
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") || t.is_sym("'{") {
*brackets += 1;
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
*brackets -= 1;
if *brackets < 0 {
return None;
}
} else if t.is_kw("begin")
|| t.is_kw("case")
|| t.is_kw("casex")
|| t.is_kw("casez")
|| t.is_kw("randcase")
|| (t.is_kw("fork") && !prev.is_some_and(|p| p.is_kw("disable") || p.is_kw("wait")))
{
*blocks += 1;
} else if t.is_kw("end")
|| t.is_kw("endcase")
|| t.is_kw("join")
|| t.is_kw("join_any")
|| t.is_kw("join_none")
{
*blocks -= 1;
if *blocks < 0 {
return None;
}
}
Some(())
}
fn ends_branch(t: &Token) -> bool {
t.is_sym(";")
|| t.is_kw("end")
|| t.is_kw("endcase")
|| t.is_kw("join")
|| t.is_kw("join_any")
|| t.is_kw("join_none")
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+11 -11
View File
@@ -32,11 +32,7 @@ impl<'a> Parser<'a> {
fn parse_stmt_inner(&mut self) -> PResult<Stmt> {
let start = self.here();
let mut meta = self.take_meta();
while self.cur().kind == TokenKind::Attribute {
meta.attrs.push(self.take_raw_text());
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
self.take_attrs(&mut meta);
let mark =
ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() };
// Nothing may leak from the statement before this one into this
@@ -86,6 +82,11 @@ impl<'a> Parser<'a> {
/// `parse_item_inner` would be scanned from the enclosing `module` or
/// `class` keyword instead.
fn split_conditional_stmt(&mut self, mark: &ItemMark, err: ParseError) -> PResult<StmtKind> {
if self.at_conditional_else_split(mark) {
if let Some(end_pos) = self.scan_if_conditional_else_extent(self.pos) {
return Ok(StmtKind::Verbatim(self.capture_split(mark, end_pos)));
}
}
if self.at_opening_split(mark) {
if let Some(end_pos) = self.scan_opening_split_extent(mark) {
return Ok(StmtKind::Verbatim(self.capture_split(mark, end_pos)));
@@ -200,18 +201,17 @@ impl<'a> Parser<'a> {
let recovered = cond.is_error();
self.expect_after_recovery(")", recovered)?;
let then = Box::new(self.body_after_recovery(recovered)?);
let mut else_directives = Vec::new();
let mut else_comments = Vec::new();
let els = if self.cur().is_kw("else") {
// Whatever was written in the gap before `else` stays on the
// keyword's left; the then-branch has already taken its own
// trailing comment.
else_comments = self.take_dangling();
let els = if let Some(gap) = self.take_else_preamble(false)? {
else_directives = gap.directives;
else_comments = gap.comments;
self.skip();
Some(Box::new(self.parse_stmt()?))
} else {
None
};
Ok(StmtKind::If { qualifier, after_kw, cond, then, else_comments, els })
Ok(StmtKind::If { qualifier, after_kw, cond, then, else_directives, else_comments, els })
}
pub(super) fn parse_case_stmt(&mut self, qualifier: Option<String>) -> PResult<StmtKind> {
+413
View File
@@ -0,0 +1,413 @@
// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Round 5B parser regression suite: `#44` generate `end`/`else` comments,
//! `#45` `` `ifdef `` between `end` and `else`, `#46` ANSI port attributes,
//! and `#42` parser leniency tightening.
use vlog_parser::ast::*;
use vlog_parser::{parse_source, parse_source_tolerant};
fn single_module(src: &str) -> Module {
let f =
parse_source(src).unwrap_or_else(|e| panic!("expected strict parse for:\n{src}\ngot: {e}"));
let (tf, diags) = parse_source_tolerant(src);
assert!(diags.is_empty(), "expected 0 tolerant diagnostics for:\n{src}\ngot: {diags:?}");
assert_eq!(format!("{f:?}"), format!("{tf:?}"), "strict/tolerant AST mismatch for:\n{src}");
let ItemKind::Module(m) = f.items.into_iter().next().expect("one item").kind else {
panic!("expected module");
};
m
}
// ----------------------------------------------------------------------
// #44 — comments between generate `end` / `end : label` and `else`
// ----------------------------------------------------------------------
#[test]
fn generate_if_keeps_trailing_comment_and_intervening_comments_before_else() {
let src = "\
module m;
if (A) begin : g_a
wire x = 1;
end : g_a // end then
// between end and else
else if (B) begin : g_b
wire x = 2;
end : g_b /* block */ // line
// before final else
else begin : g_c
wire x = 3;
end : g_c
endmodule
";
let m = single_module(src);
let ItemKind::GenIf(gi) = &m.items[0].kind else { panic!("expected GenIf") };
assert_eq!(gi.then_trailing.as_ref().map(|c| c.text.as_str()), Some("// end then"));
assert_eq!(gi.else_comments.len(), 1);
assert_eq!(gi.else_comments[0].text, "// between end and else");
let Some(GenElse::If(_, second)) = gi.els.as_deref() else {
panic!("expected GenElse::If");
};
assert_eq!(second.then_trailing.as_ref().map(|c| c.text.as_str()), Some("/* block */ // line"));
assert_eq!(second.else_comments.len(), 1);
assert_eq!(second.else_comments[0].text, "// before final else");
}
#[test]
fn generate_if_without_else_keeps_trailing_comment_on_item_meta() {
let src = "\
module m;
if (A) begin : g_only
wire x = 1;
end : g_only // keep on item
wire y;
endmodule
";
let m = single_module(src);
assert_eq!(m.items[0].meta.trailing.as_ref().map(|c| c.text.as_str()), Some("// keep on item"));
}
// ----------------------------------------------------------------------
// #45 — `` `ifdef `` and conditional directives between `end` and `else`
// ----------------------------------------------------------------------
#[test]
fn directives_between_end_and_else_stay_structural() {
let gen_src = "\
module m;
if (A) begin : g1
wire w = 1;
end : g1 // trail
`ifdef FOO // check
// mid
`endif
// before else
else begin : g2
wire w = 2;
end : g2
endmodule
";
let gm = single_module(gen_src);
let ItemKind::GenIf(gi) = &gm.items[0].kind else { panic!("expected GenIf") };
assert_eq!(gi.then_trailing.as_ref().map(|c| c.text.as_str()), Some("// trail"));
assert_eq!(gi.else_directives.len(), 2);
assert_eq!(gi.else_directives[0].raw.text, "`ifdef FOO");
assert_eq!(
gi.else_directives[0].meta.trailing.as_ref().map(|c| c.text.as_str()),
Some("// check")
);
assert_eq!(gi.else_directives[1].raw.text, "`endif");
assert_eq!(gi.else_comments.len(), 1);
assert_eq!(gi.else_comments[0].text, "// before else");
let stmt_src = "\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef BAR
`define BAZ 1
`endif
else if (b) begin
x = 2;
end else begin
x = 3;
end
end
endmodule
";
let sm = single_module(stmt_src);
let ItemKind::Always { stmt, .. } = &sm.items[0].kind else { panic!("expected always") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected block") };
let StmtKind::If { else_directives, .. } = &stmts[0].kind else { panic!("expected if") };
assert_eq!(else_directives.len(), 3);
}
#[test]
fn conditional_else_arms_after_end_parse_cleanly() {
for src in [
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef FOO
else begin
x = 2;
end
`endif
end
endmodule
",
"\
module m;
if (A) begin : g1
wire w = 1;
end : g1
`ifdef FOO
else if (B) begin : g2
wire w = 2;
end : g2
`else
else begin : g3
wire w = 3;
end : g3
`endif
endmodule
",
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef FOO
else if (b) begin
x = 2;
end
`endif
else begin
x = 3;
end
end
endmodule
",
"\
module m;
always_comb begin
unique if (a) begin
x = 1;
end
`ifdef FOO
`else
else begin
x = 2;
end
`endif
end
endmodule
",
// Non-else `` `ifdef `` following a single-branch `if` stays separate.
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef FOO
y = 2;
`endif
end
endmodule
",
// Unconditional `else if ... else ...` chain after conditional `` `ifdef ... `endif ``.
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef FOO
else if (b) begin
x = 2;
end
`endif
else if (c) begin
x = 3;
end else begin
x = 4;
end
y = 5;
end
if (A) begin : g1
wire w = 1;
end : g1
`ifdef FOO
else if (B) begin : g2
wire w = 2;
end : g2
`endif
else if (C) begin : g3
wire w = 3;
end : g3 else begin : g4
wire w = 4;
end : g4
endmodule
",
// Nested `` `ifdef ... `endif `` inside shared `else` tail after `` `else ... `endif ``.
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef FOO
else if (b) begin
x = 2;
`else
else if (c) begin
x = 3;
`endif
`ifdef INNER
x = 4;
`else
x = 5;
`endif
end
y = 6;
end
if (A) begin : g1
wire w = 1;
end : g1
`ifdef FOO
else if (B) begin : g2
wire w = 2;
`else
else if (C) begin : g2
wire w = 3;
`endif
`ifdef INNER
wire z = 1;
`endif
end : g2
endmodule
",
// Balanced directives between `else if` and trailing `else` after conditional `else`.
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef FOO
else if (b) begin
x = 2;
end
`endif
else if (c) begin
x = 3;
end
`ifdef BAR
`endif
else begin
x = 4;
end
end
endmodule
",
] {
let _ = single_module(src);
}
// Check trailing unrelated items aren't swallowed by conditional `else`.
let m_tail = single_module(
"\
module m;
always_comb begin
if (a) begin
x = 1;
end
`ifdef FOO
else begin
x = 2;
end
`endif
`ifdef AFTER
y = 3;
`endif
end
endmodule
",
);
let ItemKind::Always { stmt, .. } = &m_tail.items[0].kind else { panic!("expected always") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected block") };
assert_eq!(stmts.len(), 4, "expected verbatim if + `ifdef + y=3 + `endif, got: {stmts:?}");
// Broken / unterminated conditional `else` stays refused.
for bad in [
"module m; always_comb begin if (a) begin x = 1; end\n`ifdef FOO\nelse begin x = 2; end\nend endmodule\n",
"module m; if (A) begin end\n`ifdef FOO\nelse begin end end\n`endif\nendmodule\n",
"module m; always_comb begin if (a) begin end\n`ifdef FOO\nelse begin\n`else\nelse begin\n`endif\n`ifdef INNER\n`endif\nendmodule\n",
"module m; always_comb begin if (a) begin end\n`ifdef FOO\nelse begin x = 1; end\n`endif\nelse begin x = 2; end\nelse begin x = 3; end\nend endmodule\n",
] {
assert!(parse_source(bad).is_err(), "expected strict rejection for:\n{bad}");
}
}
// ----------------------------------------------------------------------
// #46 — attributes on ANSI ports
// ----------------------------------------------------------------------
#[test]
fn ansi_ports_accept_attributes_and_preserve_spans() {
let src = "\
module m (
(* keep *) input logic clk,
// before attr
(* mark_debug = \"true\" *) (* async_reg *) // between
output logic q,
(* keep *) logic bare_typed,
(* keep *) pkg::item_t pkg_typed,
(* keep *) bus_if.master bus
);
endmodule
";
let m = single_module(src);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI port list") };
assert_eq!(ports.len(), 5);
let p0 = ports[0].ok().expect("port 0");
assert_eq!(p0.meta.attrs.len(), 1);
assert_eq!(p0.meta.attrs[0].text, "(* keep *)");
assert_eq!(p0.name, "clk");
assert!(src[p0.span.as_range()].starts_with("(* keep *)"), "{}", &src[p0.span.as_range()]);
assert_eq!(&src[p0.name_span.as_range()], "clk");
let p1 = ports[1].ok().expect("port 1");
assert_eq!(p1.meta.attrs.len(), 2);
assert_eq!(
p1.meta.leading.iter().map(|c| c.text.as_str()).collect::<Vec<_>>(),
vec!["// before attr", "// between"]
);
assert_eq!(ports[3].ok().expect("port 3").ty.name, "pkg::item_t");
assert_eq!(ports[4].ok().expect("port 4").ty.name, "bus_if.master");
}
// ----------------------------------------------------------------------
// #42 — tightened parser leniency & preserved legal constructs
// ----------------------------------------------------------------------
#[test]
fn empty_brace_and_case_elements_and_invalid_type_casts_are_rejected() {
for bad in [
"module m; assign w = {d,, d}; endmodule\n",
"module m; assign w = {, d}; endmodule\n",
"module m; assign w = {d,}; endmodule\n",
"module m; assign w = {4{d,, d}}; endmodule\n",
"module m; assign w = {<<{d,, d}}; endmodule\n",
"module m; assign w = '{4{d,, d}}; endmodule\n",
"module m; always_comb case (x) a,, b: y = 1; endcase endmodule\n",
"module m; initial x = f(.a(y),); endmodule\n",
"module m; sub u (.a(x),); endmodule\n",
"module m; sub #(.W(1),) u (); endmodule\n",
"module m; sub u (.a(type(x)'(y))); endmodule\n",
"module m; sub #(.T(type(x)'(y))) u (); endmodule\n",
"module m; assign w = type(x)'(y); endmodule\n",
] {
assert!(parse_source(bad).is_err(), "strict parser should refuse:\n{bad}");
let (_, diags) = parse_source_tolerant(bad);
assert!(!diags.is_empty(), "tolerant parser should diagnose:\n{bad}");
}
for valid in [
"module m; logic q[$]; initial q = {}; endmodule\n",
"module m; initial f(a, , b); endmodule\n",
] {
let _ = single_module(valid);
}
// Positional trailing comma keeps its documented strict acceptance (c1076f9).
assert!(parse_source("module m; sub u (a, b,); endmodule\n").is_ok());
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+97
View File
@@ -0,0 +1,97 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# Core Path Normalization, CLI Stdin Config, JSON Format Output, and CLI Test Hardening (Round 5A)
## Goal
Deliver the Round 5A core path, CLI stdin config discovery, structured format JSON output, and CLI test hardening items (`#1`, `#11`, `#55`):
1. **Unified lexical path normalization (`#1`):** Extract `lucisv_core::path::{normalize, normalize_under}` in `crates/lucisv_core/src/path.rs` (re-exported via `crates/lucisv_core/src/lib.rs`) and replace the duplicate private normalization copies in `crates/lucisv_core/src/filelist.rs`, `crates/lucisv_core/src/config.rs`, `crates/lucisv_server/src/includes.rs`, and `crates/lucisv/src/main.rs` while preserving exact caller semantics across Unix and Windows prefixes/roots.
2. **CLI stdin config discovery & `#55`:** Ensure CLI stdin mode (`-` / `--stdin-filename <path>`) discovers and applies `lucisv.toml` / `.lucisv.toml` consistently in both `format` and `check` (including `[lint] select` and `[lint] ignore` precedence in `run_check_stdin`, rejecting empty `--stdin-filename ""`), and strengthen `a_stdin_buffer_reads_the_rule_options_too` in `crates/lucisv/tests/cli.rs` to assert explicit exit codes alongside stdout.
3. **Structured `--output-format json` for CLI format mode (`#11`):** Extend `--output-format <text|json>` to format mode (`lucisv` / `lucisv --check` / `lucisv format`), emitting a single-line JSON report with top-level `status`, `exit_code`, `summary`, and per-file `files` entries (`filename`, `status`, `cached`, `error: {category, line, column, message} | null`) while preserving existing text output and frozen `0`/`1`/`2` exit codes. Wire `tools/corpus_check.sh` and `scripts/score.sh` cleanly to consume `--output-format json` when `jq` is present (with text fallback), preserving identical TSVs and `814/6` corpus output.
## Assumptions
- Lexical normalization must never call `std::fs::canonicalize` so symlinks stay unfollowed and non-existent paths (`--stdin-filename`, rename targets) normalize identically to existing ones.
- Leading/excess `..` components on relative paths (and unrooted Windows drive-relative paths like `C:a\..\..`) are preserved, while `..` after a root directory (`/` or `C:\` or `\\server\share\`) clamps at the root.
- In format mode, `--output-format json` conflicts with `--diff`, `--stdout`, and stdin without `--check` (exiting `2`), matching `--diff` vs `--stdout` mutual exclusion so stdout is strictly one valid JSON document whenever JSON output is requested.
## Handshakes
- `crates/lucisv_core/src/path.rs` ↔ `crates/lucisv_core/src/{filelist.rs,config.rs}`, `crates/lucisv_server/src/includes.rs`, `crates/lucisv/src/main.rs`:
- `includes::normalize` re-exports `lucisv_core::path::normalize` so `crates/lucisv_server/src/file_ops.rs` continues using `crate::includes::normalize` without cross-lane edits.
- `filelist::Reader`, `config::Discovery`, and `lucisv::identity` call `lucisv_core::path::normalize_under`.
- `crates/lucisv/src/{args.rs,main.rs,lint.rs}` ↔ `tools/corpus_check.sh`, `scripts/score.sh`:
- Format JSON schema: `{"status":"ok|would-reformat|reformatted|error","exit_code":0|1|2,"summary":{"changed":N,"unchanged":N,"cached":N,"errors":N},"files":[{"filename":...,"status":"unchanged|cached|would-reformat|reformatted|error","cached":bool,"error":null|{"category":"parse-error|lex-error|verification-error|io-error|selection-error|panic","line":u32|null,"column":u32|null,"message":...}}]}`.
- Frozen `0`/`1`/`2` CLI exit codes, stderr error/summary formatting, and `corpus_check.sh` / `score.sh` TSV and stdout formats are preserved identically (`814/6`, byte-identical TSV rows).
- `crates/lucisv/tests/cli.rs`:
- `#55` closed by explicit exit-code assertions (`0` under matching config, `1` without config) in `a_stdin_buffer_reads_the_rule_options_too`, plus regression tests for stdin config discovery (`format` and `check`) and format `--output-format json`.
## Status / TODO
- [x] Implement `lucisv_core::path::{normalize, normalize_under}` and replace duplicate copies in `filelist.rs`, `config.rs`, `includes.rs`, and `main.rs`
- [x] Fix stdin `[lint] select`/`ignore` discovery and empty `--stdin-filename` handling; strengthen `#55` and add stdin format/check discovery tests
- [x] Implement format-mode `--output-format json` (`args.rs`, `main.rs`, sharing `lint::quote` / `lint::pick`), wire `tools/corpus_check.sh` and `scripts/score.sh`, and add CLI JSON tests
- [x] Enforce `<= 600` non-blank non-comment prod lines before `mod tests`, `0` `.unwrap()`/`.expect()`/`panic!`/`unsafe` in library code, author stamps, and full verification gates
## Work log
### 2026-11-26 — dev (Round 5A)
- Created `crates/lucisv_core/src/path.rs` (`normalize`, `normalize_under`) and exported `pub mod path` in `crates/lucisv_core/src/lib.rs`, with Unix, Windows prefix/root/drive-relative, and platform-independent unit tests.
- Replaced duplicate lexical normalization loops in `crates/lucisv_core/src/filelist.rs`, `crates/lucisv_core/src/config.rs`, `crates/lucisv_server/src/includes.rs` (`pub use lucisv_core::path::normalize`), and `crates/lucisv/src/main.rs` (`normalize_under`).
- Fixed `crates/lucisv/src/main.rs::run_check_stdin` to honor `[lint] select` / `[lint] ignore` via `lint::pick`, rejected empty `--stdin-filename ""` in `crates/lucisv/src/args.rs` (with `.filter(|s| !s.is_empty())` defense in `stdin_config`), and strengthened `a_stdin_buffer_reads_the_rule_options_too` (`#55`) plus new relative/`../` stdin config discovery tests in `crates/lucisv/tests/cli.rs`.
- Added `--output-format json` support to format mode (`crates/lucisv/src/{args.rs,main.rs,lint.rs}`), wired `tools/corpus_check.sh` and `scripts/score.sh` to consume `--output-format json` when `jq` is present (preserving text fallback and byte-identical TSV / `814/6` output), and added comprehensive CLI JSON tests (`unchanged`, `would-reformat`, `reformatted`, `cached`, `parse-error`, `lex-error`, `io-error`, stdin `--check`, and flag conflicts).
- Verified production line counts before `#[cfg(test)]`/`mod tests` (`path.rs` 39, `lib.rs` 7, `filelist.rs` 160, `config.rs` 313, `includes.rs` 342, `args.rs` 444, `main.rs` 550, `lint.rs` 495) and `0` `.unwrap()`/`.expect()`/`panic!`/`unsafe` in non-test production code.
### 2026-11-26 — dev (Round 5A QA fix)
- Fixed `tools/corpus_check.sh` exit-2 fallback when `use_json=1` (`jq` present) receives empty stdout (e.g. a pre-`process_file` `gather` error such as a broken `lucisv.toml`) or empty/unparseable JSON error detail: extracted shared `classify_text_error` and re-ran `"$lucisv" --check "$file" 2>&1` whenever `msg` is empty, aligning with `scripts/score.sh`.
- Verified broken `lucisv.toml` repro (`exit 2`, non-empty column-3 error message preserved) and corpus parity both with `jq` and with `jq` absent from `PATH`, plus `./tools/gates.sh --only corpus` (`814/6`), `bash -n tools/corpus_check.sh scripts/score.sh`, and `python3 tools/stamp_author.py --check`.
## QA log
### 2026-11-26 — QA (Round 5A)
**Verdict: FAIL** (one defect in `tools/corpus_check.sh` exit-2 fallback when `use_json=1` and stdout is empty).
1. **Ownership & invariants (PASS):**
- `git status --short` / `git diff --stat`: only Lane 5A files touched (`crates/lucisv_core/src/{lib.rs,path.rs,filelist.rs,config.rs}`, `crates/lucisv_server/src/includes.rs`, `crates/lucisv/src/{args.rs,lint.rs,main.rs}`, `crates/lucisv/tests/cli.rs`, `scripts/score.sh`, `tools/corpus_check.sh`, `docs/features/cli-path-r5/README.md`).
- Non-blank, non-comment production lines before `mod tests`: `path.rs` 38, `lib.rs` 7, `filelist.rs` 159, `config.rs` 312, `includes.rs` 341, `args.rs` 443, `lint.rs` 494, `main.rs` 549 (all `<= 600`), with `0` `.unwrap()`, `.expect()`, `panic!`, or `unsafe` in non-test production code.
2. **Adversarial requirement audit:**
- **`#1` (`lucisv_core::path` — PASS):** Verified `normalize` and `normalize_under` in `crates/lucisv_core/src/path.rs` (`.`/`..` folding without `canonicalize`, preserving leading/excess `..` on relative and Windows drive-relative paths like `C:a\..\..\b`, clamping `..` at Unix/Windows/UNC roots, `.`/`a/..` -> `.`, `""` -> `""`), and verified duplicate lexical loops were removed from `filelist.rs`, `config.rs`, `includes.rs` (re-exporting `lucisv_core::path::normalize`), and `main.rs` (`normalize_under`). `git grep "Component::" crates/` confirmed no remaining duplicate normalization loops in `lucisv_core`, `lucisv_server`, or `lucisv`.
- **Stdin config & `#55` (PASS):** Verified `run_check_stdin`, `stdin_config`, `args.rs`, `lint::pick`, and `crates/lucisv/tests/cli.rs` (`a_stdin_buffer_reads_the_rule_options_too` asserts explicit `0`/`1` exit codes; `stdin_discovers_config_relative_to_stdin_filename_across_cwd_and_subcommands` covers relative/`../` discovery for `format` and `check`, `[lint] select`/`ignore`, unknown config rule exit `2`, and empty `--stdin-filename ""` rejection). Adversarial binary probes confirmed CLI-over-config precedence (`--select`, `--ignore`, `--no-config`) in stdin `check` mode.
- **`#11` (`--output-format json` — FAIL on `tools/corpus_check.sh` fallback):**
- `args.rs` / `main.rs` / `tests/cli.rs`: single-line JSON schema (`status`, `exit_code`, `summary`, `files`) verified across clean (`exit 0`), dirty (`--check` `exit 1`), in-place (`reformatted`, `exit 0`), cached (`cached: true`, `exit 0`), `parse-error` / `lex-error` / `verification-error` / `io-error` / `selection-error` / `panic` (`exit 2`), stdin `--check`, and conflict rejections (`--diff`, `--stdout`, non-`--check` stdin).
- `scripts/score.sh` & `tools/corpus_check.sh` parity: on `~/.cache/lucisv-corpus` (820 files, `814/6`), both scripts produced byte-identical TSVs and outputs with `jq` vs text fallback (`PATH` without `jq`).
- **Defect (`tools/corpus_check.sh:57-102`):** When `use_json=1` (`jq` present) and `lucisv --check --output-format json "$file" 2>/dev/null` exits `2` with empty stdout (for example, a pre-`process_file` `gather` error such as a broken `lucisv.toml` in a directory), `if [ "$use_json" -eq 1 ] && [ -n "$out" ];` evaluates false and enters the `else` branch, grepping the empty `$out` instead of re-running `"$lucisv" --check "$file" 2>&1` (unlike `scripts/score.sh:184-193`). Verified with a broken `lucisv.toml` probe: `scripts/score.sh` recorded the full error message in column 4, while `tools/corpus_check.sh` emitted an empty column 3 (`other-error\t<file>\t`). Likewise, if `jq` succeeds with an empty `msg` or fails (`lines 86-92`), `corpus_check.sh` hardcodes `outcome=other-error` instead of classifying the fallback text output uniformly.
3. **Executed checks (all in worktree):**
- `python3 tools/stamp_author.py --check`: PASS (`would stamp 0 files; left 249 untouched`)
- `cargo fmt --all -- --check`: PASS
- `bash -n tools/corpus_check.sh scripts/score.sh`: PASS
- `cargo clippy -p lucisv_core -p lucisv -p lucisv_server --all-targets -- -D warnings`: PASS
- `cargo check --target x86_64-pc-windows-gnu --all-targets -p lucisv_core` (with `stable-aarch64-apple-darwin` rustup toolchain): PASS
- `./tools/guard.sh -m 8 -t 600 -- cargo test -p lucisv_core -p lucisv -p lucisv_server --all-targets`: PASS (`lucisv` unit 35 passed, `cli` 117 passed, `style_cli` 5 passed; `lucisv_core` 122 passed; `lucisv_server` unit 2082 passed / 47 ignored, `e2e` 106 passed / 3 ignored, `grammar` 3 passed, `ifdef_folding` 1 passed, `opentitan_references` 0 passed / 2 ignored)
- `./tools/gates.sh --only corpus,cross`: PASS (`corpus` `814/6`, `cross` Windows + Linux musl check pass)
### 2026-11-26 — QA re-verification (Round 5A)
**Verdict: PASS.**
- **Diff & ownership check:** Confirmed `git diff --stat` changed only `tools/corpus_check.sh` (+5 lines vs prior audit) and `docs/features/cli-path-r5/README.md`; all Rust files (`crates/lucisv_core/src/**`, `crates/lucisv_server/src/includes.rs`, `crates/lucisv/src/**`, `crates/lucisv/tests/cli.rs`) and `scripts/score.sh` are unchanged since the prior PASS checks.
- **Fix inspection (`tools/corpus_check.sh:40-108`):** Extracted `classify_text_error` and wired `if [ -z "$msg" ]; then` to re-run `"$lucisv" --check "$file" 2>&1` when `use_json=1` and classify via `classify_text_error` across empty `$out`, invalid JSON, and empty `msg`.
- **Repro & parity verification:**
- Broken `lucisv.toml` (`exit 2`, empty JSON stdout) with and without `jq` on `PATH`: both emitted identical TSV rows (`other-error .../a.sv .../lucisv.toml:1: unknown key \`bogus\` ...`), `diff -u` clean.
- Invalid-JSON fallback probe (`not-valid-json` with `exit 2`) with and without `jq` on `PATH`: both classified identically via `classify_text_error` (`parse-error .../a.sv parse error: 9:1: synthetic fallback error`), `diff -u` clean.
- **Re-executed gates:**
- `bash -n tools/corpus_check.sh scripts/score.sh`: PASS
- `python3 tools/stamp_author.py --check`: PASS (`would stamp 0 files; left 249 untouched`)
- `./tools/gates.sh --only corpus`: PASS (`814/6`, `corpus` pass)
## Review
**Lead Self-Inspect (2026-11-26): APPROVED for trunk commit.**
- Merged Lane 5A onto trunk after Round 5A QA PASS (including `tools/corpus_check.sh` `classify_text_error` fallback fix on exit 2 empty-stdout / bad-JSON cases).
- Verified `#1` (`lucisv_core::path::{normalize,normalize_under}` replacing `filelist`, `config`, `includes`, `main`), stdin config + `[lint] select/ignore` + `#55` exit codes, and `#11` (`--output-format json` + byte-identical `814/6` corpus TSV parity).
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+126
View File
@@ -0,0 +1,126 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# Parser Syntax Fixes & Parse-Once `--style auto` / Multi-Instance Layout (Round 5B)
## Goal
Deliver the Round 5B parser and formatter accuracy, throughput, and hygiene fixes across `vlog_parser` and `vlog_formatter`:
1. **Parse-once `--style auto` (`crates/vlog_formatter/src/{auto.rs, format/mod.rs, verify.rs, selection/mod.rs}`):** Lex/parse `source` and collect fenced regions once across all `PRESETS`, reuse the verified output AST/fences in `resolve_style`'s `canonical` lookup, avoid redundant re-parses in `format_range` / `format_selection`, preserve full `verify.rs` equivalence and convergence invariants, and preserve byte-identical outputs.
2. **Parser & formatter edge fixes:**
- **`#44`:** Support comments (including trailing `//` / `/* ... */ // ...` after labelled generate `end : label`) between generate `end` and `else` / `else if`.
- **`#45`:** Support `` `ifdef `` / conditional directives between `end` and `else` in both procedural `if` and generate `if` (both balanced intervening directives and conditional `else` arms).
- **`#46`:** Support SystemVerilog attributes (`(* keep *)`, multiple attributes, interleaved comments, directionless/typed/modport ANSI ports) on ANSI ports and round-trip cleanly.
- **`#42`:** Tighten parser leniency on invalid constructs (`{d,, d}`, `{, d}`, `{d,}`, `{N{a,, b}}`, `'{N{a,, b}}`, `{<<{a,, b}}`, `case a,, b:`, `f(.a(x),)`), and verify `#42a` trailing `,` in named connection lists and `#42c` `type(x)'(y)` against `scripts/score.sh` and OpenTitan `hw/` without regressing `814` corpus or `4,039/4,046` OpenTitan pass counts.
- **`#47`:** Format multi-instance declarations (`p1 u8 (...), u9 (...);`) symmetrically under `PortLists::OnePerLine` styles (`google`, `lowrisc`, `microsoft`, `nxp`) so every instance opens and closes at the same indented column instead of falling back to the asymmetric hanging layout, while preserving `PortLists::Fit` (`lucisv`, `ansi`) default output.
3. **Production safety & size hygiene:** Zero `.unwrap()`, `.expect()`, `panic!()`, or `unsafe` in non-test production code of `vlog_parser/src/**` and `vlog_formatter/src/**`, and keep all modified/added production files `<= 600` non-blank non-comment lines before `#[cfg(test)]` / `mod tests`.
## Assumptions
- Downstream crates (`vlog_semantic`, `vlog_refactor`, `vlog_linter`, `lucisv_server`, `lucisv_mcp`) pattern-match `GenElse::If(_, _)` and `GenElse::Block(_)`; keeping `GenElse`'s two tuple/struct-free signatures unchanged and adding fields to `GenIf` (`then_trailing`, `else_directives`, `else_comments`) preserves cross-crate compatibility.
- Under `PortLists::OnePerLine`, ordered/empty multi-instance declarations (`p1 u8 (), u9 ();`, `p1 u8 (a), u9 (b);`) stay flat on one line when they fit and break symmetrically (`p1\n u8 ...,\n u9 ...;`) whenever any instance's named connection list or line width breaks the declaration.
- Positional call omitted arguments (`f(a, , b)`, OpenTitan `flash_ctrl_default_region_cfg(,,,scr_en, ecc_en)`) and ordered instance trailing commas (`u(a, b,)`) are preserved per IEEE 1800 and `qa_port_entry_grace`.
## Handshakes
- `vlog_parser::ast::{GenIf, StmtKind::If}` ↔ `vlog_formatter::format::{branch, stmt}`: `GenIf` adds `then_trailing`, `else_directives`, and `else_comments`; `StmtKind::If` adds `else_directives` (staying within `ast::size_pins` bounds: `StmtKind <= 392`, `Stmt <= 552`).
- `vlog_formatter::verify` ↔ `vlog_formatter::{auto, format/mod.rs, selection/mod.rs}`: `verify::stream_from_tokens` and `verify::verify_equivalence_items` reuse pre-lexed token streams without altering `pub fn verify_equivalence`.
- `vlog_refactor::check::qa_implicit` ↔ `vlog_parser`: Tolerant error-element recovery for `.d(type(q)'(q))` and strict/tolerant trailing-comma rules from `port_entry_recovery` (`14213f6`) stay intact.
- Strict disjoint file ownership maintained: touched only `crates/vlog_parser/{src,tests}/**`, `crates/vlog_formatter/{src,tests}/**`, and `docs/features/parser-formatter-r5/README.md`.
## Status / TODO
- [x] Refactor `auto.rs` / `format/mod.rs` / `verify.rs` / `selection/mod.rs` for parse-once `--style auto`, `resolve_style`, `format_range`, and `format_selection`
- [x] Fix `#44` comments (including trailing `//` after labelled generate `end : label`) between generate `end` and `else`
- [x] Fix `#45` `` `ifdef `` and conditional directives between `end` and `else` (procedural and generate `if`)
- [x] Fix `#46` attributes on ANSI ports in `vlog_parser` and `vlog_formatter`
- [x] Tighten `#42b` empty brace/case elements + `f(.a(x),)` and verify `#42a`/`#42c` against corpus and OpenTitan `hw/`
- [x] Fix `#47` multi-instance declarations under `PortLists::OnePerLine`
- [x] Eliminate remaining non-test `.unwrap()` calls in `format/decl.rs` and `format/item.rs` and verify `<= 600` production line counts
- [x] Add regression suites `crates/vlog_parser/tests/parser_r5.rs` and `crates/vlog_formatter/tests/formatter_r5.rs` and pass all CI/OpenTitan gates
## Work log
### 2026-11-26 — dev (Round 5B)
- **Baseline (`6d1c689`):**
- OpenTitan `/Users/lucio/repo/opentitan/hw` (4,046 files, `--style auto --check --no-cache`): `5.040 s` wall (`39.06 s` user, `3.03 s` sys, `835%` CPU); `3967` would reformat, `72` unchanged, `7` failed (4,039 passing, 0 verification failures).
- OpenTitan default (`--style lucisv`): `0.981 s` wall (`6.80 s` user, `0.63 s` sys); `3967` reformatted, `72` unchanged, `7` failed. Snapshotted all 4,039 formatted outputs to `/tmp/r5b_base_ot_default` before editing.
- Corpus (`./tools/gates.sh --only corpus`): `PASS` (`814/6`, `2 s`).
- **Parse-once `--style auto` (`auto.rs`, `format/mod.rs`, `verify.rs`, `selection/mod.rs`):**
- Added `format::parse_once`, `format::render_parsed`, `format::verify_rendered`, `verify::stream_from_tokens`, and `verify::verify_equivalence_items`; switched `Fmt::{regions, splits}` to borrowed slices.
- Updated `auto::closest_inner` to lex/parse `source` once, render all 6 `PRESETS` on the shared `(file, regions)`, short-circuit on `output == source`, rank remaining candidates using reusable `LineCounter` (`total_a + total_b - 2*matched`), verify only the winning candidate (preserving earliest-preset error priority if all fail), and reuse `(out_file, out_regions)` in `canonical_parsed`.
- Updated `format_range` and `format_selection` via `auto::resolve_concrete` to reuse the parsed input AST under `auto`.
- Post-change OpenTitan `--style auto --check --no-cache` benchmark (3 runs): `2.991 s`, `2.758 s`, `2.660 s` (`17.55 s` user, `1.81 s` sys, `727%` CPU) — **~1.9x wall / ~2.2x user CPU faster** than `6d1c689` (`5.040 s` / `39.06 s`) and **~2.05x faster** than historical `5.46 s`, with **0 diff lines** on stdout/stderr vs `6d1c689`.
- **`#44` & `#45` (`ast/{module,stmt}.rs`, `parser/{directive,item,stmt,split}.rs`, `format/{branch,stmt}.rs`):**
- Added `GenIf::{then_trailing, else_directives, else_comments}` and `StmtKind::If::else_directives`; added `Parser::take_else_preamble`, `has_else_past_directives`, and `take_else_directives` in `directive.rs`.
- Added `Parser::{at_conditional_else_ahead, at_conditional_else_split, scan_if_conditional_else_extent}` in `split.rs` to capture conditional `else` inside `` `ifdef `` / `` `ifndef `` (balanced blocks/brackets/`` `endif ``s, rival `` `else `` arms, optional trailing unconditional `else`) verbatim while leaving unterminated/unbalanced cases rejected and non-`else` `` `ifdef ``s separate.
- Updated `format/branch.rs` with shared `push_else_keyword` and `gen_then_branch` (detecting merged `/* a */ // b` line-ending trailing comments on generate blocks).
- **`#46` (`parser/{cursor,decl,module,item,stmt,instance}.rs`, `format/module.rs`):**
- Extracted `Parser::take_attrs` (draining both same-line `pending_trailing` and next-line `tok.leading` into `meta.leading`), reused across `item`, `stmt`, `instance`, and `parse_ansi_port`.
- Added `at_typed_declarator_at` and `at_modport_port_at` so `parse_port_list` skips leading `(* ... *)` attributes when detecting ANSI port lists (including directionless, `pkg::type`, and `intf.modport` ports).
- Updated `format/module.rs` (`ansi_port_item`, `ansi_port_cells`, `ansi_port_plain`) to render ANSI port attributes and preserve any comments interleaved between/after attributes without breaking token order or joining alignment groups.
- **`#42` (`parser/{primary,instance,randsequence}.rs`):**
- **#42b:** Tightened `Parser::parse_expr_item` / `parse_expr_list` via `parse_expr_item_with(allow_omitted: bool)` so empty elements are accepted only in parenthesized argument lists (`close == ")"` and not after `NamedArg`), rejecting `{d,, d}`, `{, d}`, `{d,}`, `{4{d,, d}}`, `{<<{d,, d}}`, `'{4{d,, d}}`, `case a,, b:`, and `f(.a(x),)` while preserving `{}` and omitted positional call args (`f(a, , b)`).
- **#42a:** Confirmed named port/override trailing commas (`.a(x),)`, `#(.W(1),)`) are already refused strictly and reported tolerantly by `note_trailing_comma` (`port_entry_recovery.rs`); tightened `f(.a(x),)` named call trailing commas, keeping `directives_in_lists` `,` before `` `ifdef `` and IEEE 1800 positional `u(a, b,)` untouched (`0` matches in OpenTitan/corpus for dangling `,` before `` `ifdef ... `endif ) ``).
- **#42c:** Confirmed malformed `type(x)'(y)` in connections, overrides, and expressions (`sub u (.a(type(x)'(y)))`, `sub #(.T(type(x)'(y)))`, `assign w = type(x)'(y)`) is already rejected strictly (`unexpected keyword 'type' in expression`) and diagnosed tolerantly (`qa_implicit.rs` pins `.d(type(q)'(q))` recovery).
- **`#47` (`format/instance.rs`):**
- Under `PortLists::OnePerLine`, placed multi-instance declarations inside `group(vec![indent(inner)])` starting with `Doc::Line` (`!on_fresh_line`), so broken multi-instance statements indent every instance (`u8`, `u9`, ...) uniformly and align each instance's closing `)` with its own opening line (`google` 2/4/8, `lowrisc`/`nxp` 2/4/6, `microsoft` 4/8/12) while keeping `PortLists::Fit` (`lucisv`, `ansi`) byte-identical.
- **Safety & file-size audit:** Eliminated the remaining 2 non-test `.unwrap()` calls in `format/decl.rs` and `format/item.rs` using `TryFrom<[ListItem; 1]>` and `saturating_sub`; verified `0` `.unwrap()`, `.expect()`, `panic!()`, or `unsafe` in non-test production code across `vlog_parser/src/**` and `vlog_formatter/src/**`, and verified all production files remain `<= 600` non-blank non-comment lines (`item.rs` 589, `module.rs` 568, `instance.rs` 565, `stmt.rs` 564).
### 2026-11-26 — dev QA-fix (Round 5B)
- Fixed QA `#45` defect 1 (`crates/vlog_parser/src/parser/split.rs` + `directive.rs`): unified `else_past_directives_at` in `directive.rs`, changed `scan_uncond_branch` to return `(usize, bool /* is_if */)`, and made `scan_if_conditional_else_extent` loop across `cond_else_at(i)`, optional balanced directives before `else`, and any chained `else if (...) ... else ...` branches while stopping cleanly on non-`else` `` `ifdef ``s or a non-`if` `else` terminator.
- Fixed QA `#45` defect 2 (`crates/vlog_parser/src/parser/split.rs::scan_cond_else_region`, `scan_uncond_branch`): added explicit `outer_open: bool` state (distinct from nested `cond` depth) and nested `` `else `` / `` `elsif `` skipping at `cond > 0` so balanced nested `` `ifdef ... `endif `` directives inside a shared `else` tail scan cleanly through the closing `end` / `;` instead of exiting prematurely when nested `cond` returns to `0`.
- Added regression tests covering both procedural and generate variants, balanced intervening directives inside `else if ... else` chains, nested `` `ifdef ... `else ... `endif `` inside shared tails, and negative/unterminated bounds in `crates/vlog_parser/tests/parser_r5.rs` and `crates/vlog_formatter/tests/formatter_r5.rs`.
## QA log
### 2026-11-26 — dev verification (self-check)
- `crates/vlog_parser/tests/parser_r5.rs`: 6/6 passed (`#44`, `#45` directives + conditional `else` + negatives, `#46`, `#42a/b/c`).
- `crates/vlog_formatter/tests/formatter_r5.rs`: 5/5 passed (all 6 presets + `auto` verification/idempotency/layout pins + `resolve_style`/`format_range`/`format_selection`).
- `auto_sweep` over `/Users/lucio/repo/opentitan/hw`: `4,047` files scanned, `7` refused (pre-existing parse errors), `0` crashes, `0` non-idempotent, `0` second-run preset renames (`lucisv: 3379`, `lowrisc: 526`, `microsoft: 80`, `google: 30`, `nxp: 21`, `ansi: 4`).
- Default-style (`--style lucisv`) OpenTitan diff against pre-edit snapshot (`/tmp/r5b_base_ot_default` vs `/tmp/r5b_new_ot_default`): `0` differing files across all 4,039 passing files; `--style auto` output `0` diff lines vs baseline.
- `./tools/gates.sh --only corpus`: `PASS` (`814/6`, `2 s`).
- `cargo fmt --all -- --check`, `python3 tools/stamp_author.py --check`, `cargo clippy -p vlog_parser -p vlog_formatter --all-targets -- -D warnings`, `./tools/guard.sh -m 8 -t 600 -- cargo test -p vlog_parser -p vlog_formatter -p vlog_semantic -p vlog_refactor -p vlog_linter --all-targets`: see final gate run after README addition.
### 2026-11-26 — Round 5 Lane 5B QA audit (`FAIL`)
- **Verdict: `FAIL`** (two edge-case defects found in `#45` conditional-`else` extent scanning in `crates/vlog_parser/src/parser/split.rs`; all invariants, gates, OpenTitan/corpus benchmarks, parse-once `--style auto`, `#44`, `#46`, `#42`, and `#47` passed).
- **Defects found in `crates/vlog_parser/src/parser/split.rs`:**
1. `scan_if_conditional_else_extent` (`split.rs:640-655`): When a conditional `` `ifdef ``/`` `ifndef `` `else` arm is followed by an unconditional `else if (...)` branch that is itself followed by an unconditional `else` (either generate `if` or procedural `if`), `scan_uncond_branch` stops after the `else if` branch at the trailing `else`, and `scan_if_conditional_else_extent` only continues the loop when `self.cond_else_at(i)` is true, leaving the trailing `else` orphaned and failing with `unsupported construct/statement starting with keyword 'else'`.
2. `scan_cond_else_region` (`split.rs:657-698`): When a conditional `else` region opens a block/bracket in its first arm and hits `` `else ``/`` `elsif `` with `blocks > 0` or `brackets > 0` (setting `cond = 0` at `split.rs:683` to scan past `` `endif `` to the closing `end`/`;`), any nested balanced `` `ifdef ... `endif `` inside that shared tail increments `cond` to `1` and decrements back to `0`, hitting `if cond == 0 { return (brackets == 0 && blocks == 0).then_some(i + 1); }` (`split.rs:675-677`) and returning `None` prematurely instead of continuing to the branch closer (failing cleanly with `conditional 'else' after 'if'`).
- **Checks verified in worktree (HEAD `6d1c689`):**
- Ownership & invariants: Only Lane 5B paths modified/created (`crates/vlog_parser/{src,tests}/**`, `crates/vlog_formatter/{src,tests}/**`, `docs/features/parser-formatter-r5/README.md`). All 23 changed library `.rs` files are `<= 600` non-blank non-comment production lines before `#[cfg(test)]`/`mod tests` (max `589` in `crates/vlog_parser/src/parser/item.rs`). `0` occurrences of `.unwrap()`, `.expect()`, `panic!`, or `unsafe` in non-test production code across `crates/vlog_parser/src/**` and `crates/vlog_formatter/src/**`.
- `cargo fmt --all -- --check`: PASS.
- `python3 tools/stamp_author.py --check`: PASS (`would stamp 0 files; left 249 untouched`).
- `cargo clippy -p vlog_parser -p vlog_formatter --all-targets -- -D warnings`: PASS.
- `./tools/guard.sh -m 8 -t 600 -- cargo test -p vlog_parser -p vlog_formatter -p vlog_semantic -p vlog_refactor -p vlog_linter --all-targets`: PASS (`2,787` passed, `0` failed, `12` ignored — `vlog_formatter`: `381`, `vlog_linter`: `672`, `vlog_parser`: `527` + `2` ignored, `vlog_refactor`: `769` + `6` ignored, `vlog_semantic`: `438` + `4` ignored).
- `./tools/gates.sh --only corpus`: PASS (`814/820`, `0` verification errors, `0` crashes, `3 s`).
- OpenTitan `/Users/lucio/repo/opentitan/hw` (`target/release/lucisv`): default `--check --no-cache` (`3,967` would reformat, `72` unchanged, `7` pre-existing lex/parse failures = `4,039/4,046` pass, `0` verification failures); `--style auto --check --no-cache` (`3,967` would reformat, `72` unchanged, `7` pre-existing lex/parse failures = `4,039/4,046` pass, `0` verification failures); `auto_sweep` (`4,047` files, `7` refused, `0` crashes, `0` non-idempotent, `0` second-run renames; `lucisv: 3379, lowrisc: 526, microsoft: 80, google: 30, nxp: 21, ansi: 4`). `/Users/lucio/repo/opentitan` `git status --porcelain` is empty.
- Parse-once `--style auto`, `#44`, `#46`, `#42`, `#47`: All explicit requirements and adversarial stdin probes passed (apart from the two `#45` `split.rs` edge cases above).
### 2026-11-26 — Round 5 Lane 5B QA re-audit (`PASS`)
- **Verdict: `PASS`** (both prior `#45` defects in `crates/vlog_parser/src/parser/split.rs` and `directive.rs` are fixed and verified; all invariants, tests, corpus, and OpenTitan gates pass).
- **Re-audit of `#45` fixes (`crates/vlog_parser/src/parser/{split.rs,directive.rs}`, `crates/vlog_parser/tests/parser_r5.rs`, `crates/vlog_formatter/tests/formatter_r5.rs`):**
- `scan_if_conditional_else_extent` (`split.rs:640-660`) + `else_past_directives_at` (`directive.rs:218-247`) + `scan_uncond_branch` (`split.rs:720-779`): Confirmed unconditional `else if (...) ... else ...` chains (with or without balanced directives before `else`) after conditional `` `ifdef `` / `` `ifndef `` `else` arms parse and format idempotently across both procedural and generate `if`, while outer `else` branches (`if (outer) if (inner) ...`) and trailing non-`else` `` `ifdef `` blocks remain unswallowed.
- `scan_cond_else_region` (`split.rs:662-718`): Confirmed `outer_open` tracking and nested `` `else `` / `` `elsif `` skipping at `cond > 0` allow balanced nested `` `ifdef ... `else ... `endif `` inside shared `else` tails to scan cleanly through the closing `end` / `;` while rejecting stray `` `else `` / `` `endif ``, unbalanced directives, and unmatched `end`/`else`.
- **Invariants & gates verified in worktree (HEAD `6d1c689`):**
- Ownership & sizes: Strictly Lane 5B files (`crates/vlog_parser/{src,tests}/**`, `crates/vlog_formatter/{src,tests}/**`, `docs/features/parser-formatter-r5/README.md`). All 23 changed library `.rs` files remain `<= 600` production LOC (`item.rs` 589, `stmt.rs` 570, `module.rs` 568, `instance.rs` 565, `split.rs` 554, `directive.rs` 265). `0` non-test `.unwrap()`, `.expect()`, `panic!`, or `unsafe` across `crates/vlog_parser/src/**` and `crates/vlog_formatter/src/**`.
- `cargo fmt --all -- --check`: PASS.
- `python3 tools/stamp_author.py --check`: PASS (`would stamp 0 files; left 249 untouched`).
- `cargo clippy -p vlog_parser -p vlog_formatter --all-targets -- -D warnings`: PASS.
- `./tools/guard.sh -m 8 -t 600 -- cargo test -p vlog_parser -p vlog_formatter -p vlog_semantic -p vlog_refactor -p vlog_linter --all-targets`: PASS (`2,787` passed, `0` failed, `12` ignored — `vlog_formatter`: `381`, `vlog_linter`: `672`, `vlog_parser`: `527` + `2` ignored, `vlog_refactor`: `769` + `6` ignored, `vlog_semantic`: `438` + `4` ignored).
- `./tools/gates.sh --only corpus`: PASS (`814/820`, `0` verification errors, `0` crashes, `3 s`).
- OpenTitan `/Users/lucio/repo/opentitan/hw` (`target/release/lucisv --style auto --check --no-cache`): `3,967` would reformat, `72` unchanged, `7` failed (pre-existing lex/parse errors = `4,039/4,046` pass, `0` verification failures); `/Users/lucio/repo/opentitan` `git status --porcelain` is empty.
## Review
**Lead Self-Inspect (2026-11-26): APPROVED for trunk commit.**
- Merged Lane 5B onto trunk after Round 5B QA Re-Audit PASS (including `#45` `split.rs` conditional-`else` fixes for trailing `else if ... else ...` chains and nested `` `ifdef `` inside shared tails).
- Verified parse-once `--style auto` (`~2.66-3.01 s` vs `5.04-5.46 s` baseline across 4,046 OpenTitan `hw/` files, `0` verification failures, default `--style lucisv` byte-identity on all `4,039` passing OpenTitan files, `0` non-test `.unwrap()` calls across `vlog_parser` & `vlog_formatter`, and `814/6` corpus PASS).
- Updated `crates/lucisv_mcp/src/tools/place.rs` test `what_a_placement_cannot_see_or_would_change_is_refused` after `#46`: `(* keep *) b` now parses cleanly as an attributed port inheriting direction from `a`, while `123 b` exercises the unreadable `ListElem::Error` refusal path.
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+8 -8
View File
@@ -737,7 +737,7 @@ update the filing README(s) and this file.
| # | request | filed by | owner it waits on |
|---|---|---|---|
| 1 | `lucisv_core::path::normalize` — one `.`/`..` folding instead of three private copies (`filelist::Reader::normalize`, `config::Discovery::absolute`, `includes::normalize`, the last now `pub`) | include-nav; restated by file-operations | lucisv_core |
| ~~1~~ | ~~`lucisv_core::path::normalize` — one `.`/`..` folding instead of three private copies (`filelist::Reader::normalize`, `config::Discovery::absolute`, `includes::normalize`, the last now `pub`)~~ — **closed 2026-11-26 by `cli-path-r5` (Round 5A):** added `lucisv_core::path::{normalize, normalize_under}` handling Unix and Windows prefixes/roots and replaced the duplicate copies in `filelist.rs`, `config.rs`, `lucisv_server/src/includes.rs`, and `lucisv/src/main.rs`. | include-nav; restated by file-operations | ~~lucisv_core~~ done |
| ~~2~~ | ~~A span for `DataType` (and `ExprKind::Cast::ty` tails) — the last thing keeping `vlog_semantic/src/scan.rs` alive~~ — **delivered 2026-09-05 by type-name-spans (TODO §47):** `DataType::name_span()` (a `u32` start paired with `name.len()`, so `Expr` stays inside its 96-byte pin) and `DataType::segments()` (the `::`/`.` split from the span's own text); `StmtKind::Disable` carries its target's span. `scan.rs` is deleted; `analyze`'s `src` stays as `Binder::exact_or_empty`'s verification oracle — a segment whose derived range does not read back is recorded with the empty range (counted *unplaced* by the census, never dropped). The census pin covers type-name references. | vlog-semantic (item 2); restated by class-semantics | vlog_parser |
| ~~3~~ | ~~`fence::scan_nested` has no `ItemKind::Class` arm — formatter fences are inert inside class bodies (the `--fix` backstop still holds; asymmetry errs hands-off)~~ — **delivered 2026-09-02 by statement-fences (TODO §31)**: `scan_nested` enters class bodies, functions, tasks, `always`/`initial`/`final`; statement lists (`begin…end`, `fork…join`, every compound body) are fenceable through `scan_stmt_scope`/`scan_nested_stmt` on the shared `scan_units`; `stmt_docs`/`stmt_seq` obey the two swallowed-unit rules; fence regions merge into `range.rs`'s plan (load-bearing — a fenced statement has no verbatim run behind it). A region opens only at a line start (`opens_line`), so `module m; // lucisv: off` no longer opens one — the rule the format-fences README has stated since round 1. Deferred with reasons: port lists, case-item label lists, same-line fences, `PropSeqDecl.locals`. Opentitan: 4 of its 9 fenced files now keep their fenced bytes. | classes | ~~vlog_formatter (fence.rs)~~ done |
| ~~4~~ | ~~A `lint` key in `lucisv.toml` (`[lint.<rule>]` config; selected-rules list) with CLI>config precedence~~ — **delivered 2026-09-02 by semantic-lints-on**: `[lint] select = […] / ignore = […]` in `lucisv.toml` (CLI over config, key by key; unknown rule names fail the run naming the file; `[lint.<rule>]` tables rejected by name — per-rule config was delivered later by linter-expansion-2, v0.38.0; the earlier rejection described here is historical) and `lucisv.lint.select/ignore` settings (registry-validated, republish on change). | linter-core; restated by lint-rules-2, semantic-lints, server-lint | ~~config-discovery / lucisv_core~~ done |
@@ -747,7 +747,7 @@ update the filing README(s) and this file.
| ~~8~~ | ~~Symlink-cycle detection in the shared walk (both front ends exposed; wants its own round — it changes CLI behavior)~~ — **delivered 2026-09-05 by walk-cycles (TODO §43.1):** `Walk` keeps a `visited` set keyed on `(dev, ino)` (canonical path elsewhere); each directory entered once, a link to one already entered skipped, a link to one not yet entered followed once, a dangling directory link skipped (a dangling source-file link is still handed on so the front end's "no such file" survives). Both front ends. | lucisv-core-lift | lucisv_core |
| ~~9~~ | ~~Chasing `InheritedCandidate` through the member tables (in-file and cross-file) + hover for `extends`~~ — **delivered 2026-09-01 by class-member-access**: `resolve::member_in_chain` walks the in-file `extends` chain, `WorkspaceIndex::base_of` + `member_chain` walk it across files (inside `follow_one`, so hover and cross-file references agree), both cycle-guarded; `this.x`/`super.x` misses ride the same loop. `extends` hover/definition on the base name was already answered by overlay-promotion's type-position promotion. Residue filed in TODO §15 round 2: a `base` field on `ReferenceFact` so `this.x` misses get index postings too | class-semantics | ~~vlog_semantic~~ done |
| ~~10~~ | ~~`Fmt::raw_text`'s string-crossing path emits a `Doc::Text` carrying newlines~~ — **delivered 2026-08-26 (`53f2269`)**: both `raw_text` and the parameterized-type `#( … )` now emit `Doc::Inline`, whose printer arm resumes measuring from the text's own last line. directive-split's README (QA round 3 note) still documents it as open and should be struck there too | directive-split QA | ~~vlog_formatter~~ done |
| 11 | Corpus scripts match `parse error:` / `lex error:` / `verification failed:` textually; a structured `--output-format json` for format mode would remove it | corpus-check | crates/lucisv |
| ~~11~~ | ~~Corpus scripts match `parse error:` / `lex error:` / `verification failed:` textually; a structured `--output-format json` for format mode would remove it~~ — **closed 2026-11-26 by `cli-path-r5` (Round 5A):** added `--output-format json` for CLI format mode (`main.rs`/`args.rs`, preserving frozen 0/1/2 exit codes) and wired `tools/corpus_check.sh` + `scripts/score.sh` to consume JSON with `classify_text_error` text fallback. | corpus-check | ~~crates/lucisv~~ done |
| 12 | `vlog_refactor::scope::Scope::build` re-derives sort-and-dedup by hand; could call `index_order` | indexing-ux | vlog_refactor |
| ~~13~~ | ~~Anonymous-aggregate members (`enum {A,B} x;`) not declared as symbols — hover/definition gap~~ — **delivered 2026-09-01 by struct-members**: anonymous enum variants land in the enclosing scope via the shared `bind_enum_body`; an anonymous `struct {…} s;` declarator and every inline nested struct field carry their own `Struct` child scope, and `member_scope` accepts any symbol whose child scope is a `Struct` scope. Residue filed in the struct-members README: cross-file anonymous struct *variables*, `typeDefinition` inside an anonymous aggregate written as a data declaration | types-decls | ~~vlog_semantic~~ done |
| ~~14~~ | ~~A `program` node with `name_span`/`end_label_span` for linked editing~~ — **delivered by vendor-formal-grammar (0.30.0)**: `parser/item.rs` routes `program` to `parse_module("endprogram")`; the resulting `ItemKind::Module` carries both spans and `linked.rs::module_pairs` consumes them. Confirmed in the 2026-09-04 source audit. | linked-editing | ~~vlog_parser~~ done |
@@ -778,12 +778,12 @@ update the filing README(s) and this file.
| ~~39~~ | ~~**MCP-10 → `vlog_refactor`:** `extract_module` writes LF into a CRLF file (`extract/render.rs`)~~ — **closed 2026-11-26 by `refactor-correctness-r1` (Round 1):** `extract/mod.rs` and `extract/render.rs` detect source `\r\n` vs `\n` and preserve it across new-module, instantiation, and same-file insertion. | mcp-edit-tools | ~~vlog_refactor~~ done |
| ~~40~~ | ~~**MCP-11/12 → `vlog_refactor`/`vlog_semantic`:** a batched `find_references` for several declarations; `find_references` misses a hierarchical use into a generate loop (`gen_l[0].z`)~~ — **second half answered 2026-09-30 by generate-label-rename (TODO §65.1, row 43); closed 2026-11-26 by `mcp-hardening-r3` (Round 3):** `find_references_batch` and `find_references_batch_with` reuse one `Scope::build_keeping` across queries. | mcp-structural-edits | ~~vlog_refactor, vlog_semantic~~ done |
| 41 | **MCP-13 → `vlog_linter`:** a forced deletion of a non-ANSI body port leaves a header port with no direction and no lint reports it | mcp-structural-edits | vlog_linter |
| 42 | **Parser leniency → `vlog_parser`:** a trailing `,` in a named connection list, an empty concatenation element `{d,, d}`, and `type(x)'(y)` in a connection parse without a diagnostic (the rename verifier's position rule covers the rename; every other splice contract is exposed) | refactor-rename (M3.5) | vlog_parser |
| ~~42~~ | ~~**Parser leniency → `vlog_parser`:** a trailing `,` in a named connection list, an empty concatenation element `{d,, d}`, and `type(x)'(y)` in a connection parse without a diagnostic (the rename verifier's position rule covers the rename; every other splice contract is exposed)~~ — **closed 2026-11-26 by `parser-formatter-r5` (Round 5B):** tightened omitted-element rules (`{d,, d}`, `{, d}`, `{d,}`, `{N{d,, d}}`, `'{N{d,, d}}`, `case a,, b:`, `f(.a(x),)` rejected while keeping IEEE 1800 positional `u(a, , b)` / `u(a, b,)`), while named-connection/override trailing commas and `type(x)'(y)` fail strict parsing and report tolerant diagnostics. | refactor-rename (M3.5) | ~~vlog_parser~~ done |
| ~~43~~ | ~~**MCP-14 → `vlog_refactor`/`vlog_semantic`:** rename of a generate block label leaves hierarchical paths through it unrewritten and `find_references` does not report them — vlog_refactor/vlog_semantic; the MCP layer refuses the rename; the LSP still allows it~~ — **closed 2026-09-30 by generate-label-rename (TODO §65.1, 0.60.0):** the gap was resolution, not the rename — `vlog_semantic` now declares a `for` block's label in the enclosing scope (the genvar stays in the header), treats `generate … endgenerate` as no scope, gives a named block a member scope, walks an index in a path as the name it indexes, and puts blocks on a module's hierarchical surface with their members under the synthesized key `module.label` (`FACTS_FORMAT` 21; `Semantics::member_key`, which `lucisv_server/src/nav.rs` now asks with). Every segment — bare, indexed, nested, cross-file — and the closing label are ordinary references, so `find_references`, `rename` (LSP, CLI engine, MCP) and the verifier's unchanged resolution print all see them; no verifier normalization was added, eight attacks pin that (`check/qa_block_paths.rs`). `lucisv-mcp`'s `block` refusal is lifted. Also answers row 40's second half (`gen_l[0].z` is found). | mcp-lean-catalogue | vlog_refactor, vlog_semantic |
| 44 | **A comment between a generate `end` and `else`** (also a trailing `// c` after a labelled generate `end` before `else`) is a verification error, so the file is left unformatted — the safety net works, the formatter should not need it. Present in 0.65.4 (TODO §71 wave 4) | format-styles (QA) | vlog_parser / vlog_formatter |
| 45 | **`` `ifdef `` between `end` and `else` is a parse error** (TODO §71 wave 4) | format-styles (QA) | vlog_parser |
| 46 | **An attribute on an ANSI port** (`(* keep *) input a`) is a parse error (TODO §71 wave 4) | format-styles (QA) | vlog_parser |
| 47 | **Multi-instance declarations under one-per-line styles** (`p1 u8 (...), u9 (...)`) get the hanging layout instead of the style's (TODO §71 wave 4; CHANGELOG 0.65.5 known limit) | format-styles (QA) | vlog_formatter |
| ~~44~~ | ~~**A comment between a generate `end` and `else`** (also a trailing `// c` after a labelled generate `end` before `else`) is a verification error, so the file is left unformatted — the safety net works, the formatter should not need it. Present in 0.65.4 (TODO §71 wave 4)~~ — **closed 2026-11-26 by `parser-formatter-r5` (Round 5B):** `GenIf` owns `then_trailing`, `else_directives`, and `else_comments`; comments between generate `end` / `end : label` and `else` format cleanly with zero verification errors. | format-styles (QA) | ~~vlog_parser / vlog_formatter~~ done |
| ~~45~~ | ~~**`` `ifdef `` between `end` and `else` is a parse error** (TODO §71 wave 4)~~ — **closed 2026-11-26 by `parser-formatter-r5` (Round 5B):** handled balanced intervening directives (`take_else_directives`) and balanced conditional `else` arms (`scan_if_conditional_else_extent` / `scan_cond_else_region`) across both generate and procedural `if`. | format-styles (QA) | ~~vlog_parser~~ done |
| ~~46~~ | ~~**An attribute on an ANSI port** (`(* keep *) input a`) is a parse error (TODO §71 wave 4)~~ — **closed 2026-11-26 by `parser-formatter-r5` (Round 5B):** `Parser::take_attrs` and `ansi_port_item` parse and format ANSI port attributes cleanly. | format-styles (QA) | ~~vlog_parser~~ done |
| ~~47~~ | ~~**Multi-instance declarations under one-per-line styles** (`p1 u8 (...), u9 (...)`) get the hanging layout instead of the style's (TODO §71 wave 4; CHANGELOG 0.65.5 known limit)~~ — **closed 2026-11-26 by `parser-formatter-r5` (Round 5B):** `format/instance.rs` indents multi-instance declarations symmetrically under `PortLists::OnePerLine` while leaving `Fit` unchanged. | format-styles (QA) | ~~vlog_formatter~~ done |
| ~~48~~ | ~~**Directory-only watcher events.** VS Code coalesces deletes under a removed folder into one folder event and the client's `**/*.{v,vh,sv,svh}` filter drops it, so the server receives nothing; a folder moved in is dropped likewise. Wanted: a second registration (`**/*`, `Create \| Delete`) and a handler expanding a folder to the held files and include lines under it — changes every client's registration and traffic, the owner's call (TODO §71 waves 5–6)~~ — **closed 2026-11-26 (won't-fix by owner ruling):** rely on VS Code; no second watcher registration added. | localized-reindex (QA P1); scan-ordering | ~~owner decision~~ won't-fix |
| ~~49~~ | ~~**A buffer the scope would not take stays indexed after `didClose`** (excluded or unlisted, taken in by a scan or the one-file path), and **closing an unsaved in-scope buffer a rescan indexed leaves its text in the index** (QA-7a). One root: a close does not touch the index. A one-file remove costs ~225 ms on OpenTitan (fixed and reverted in scan-ordering); wanted: a cheap removal, e.g. a tombstone the next scan or publish folds in (TODO §71 waves 5–6)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2):** `WorkspaceIndex::remove_file` tombstones slots in-place via `replace_facts`, `live_files()` skips tombstones across all callers (`sources.rs`, `candidates.rs`, `lucisv_mcp`), and `DidCloseTextDocument` calls `close_and_reconcile` (2,000 cycles on 4k index at ~2.98 ms / 112.6 µs). | localized-reindex (QA P2); scan-ordering (QA-1, QA-7a) | ~~vlog_semantic / lucisv_server~~ done |
| ~~50~~ | ~~**An unheld buffer opened while a scan runs is never taken in** by that scan or afterwards; opened before the scan it is held — the same final state answers differently by timing (TODO §71 wave 6)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2):** `reconcile_open_buffers_into`, `ScanAbsorbed`, and `closing_affects_running_scan` reconcile mid-scan opens/edits/closes to match pre-scan opens. | scan-ordering (QA-2) | ~~lucisv_server (`state/`)~~ done |
@@ -791,7 +791,7 @@ update the filing README(s) and this file.
| ~~52~~ | ~~**A request held during a scan is answered against the newest text**, so a position-based request can resolve a different symbol when an edit moved the text under it; rename edits carry no document version for the client to reject (TODO §71 wave 6)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `Document` tracks client `version: Option<i32>`, and `ports::encode_edit` (shared by `rename.rs` and `ports.rs`) emits versioned `DocumentChanges::Edits` preserving open client URIs when `workspace.workspaceEdit.documentChanges` is advertised. | scan-ordering (QA) | ~~lucisv_server (`server/`, `rename.rs`)~~ done |
| ~~53~~ | ~~**Renaming a port of a module defined twice** gives an edit or a refusal at random across fresh servers (`top_englishbreakfast/ip/ast/rtl/adc.sv:81`, `qa717/drv/dup.py`); not diagnosed (TODO §71 wave 6)~~ — **closed 2026-11-26 by Round 1 (`refactor-correctness-r1` + `server-ordering-r1`):** `lucisv_server` holds workspace-wide mutating requests (`rename`, `codeAction/resolve`, `executeCommand`, `willRenameFiles`) in `after_scan` across `self.scanning`, and `vlog_refactor::rename` + `preflight` + `same_file::renamed_here` refuse members inside duplicated file-scope units; verified 10/10 deterministic on OpenTitan `adc.sv:81`. | scan-ordering (QA-7c) | ~~vlog_refactor / lucisv_server~~ done |
| ~~54~~ | ~~**`lucisv-mcp` re-reads a file with a future mtime on every call**, forever (67 ms against 7 ms per `find` on 4 000 files) — the racy rule never settles (TODO §70)~~ — **closed 2026-11-26 by `mcp-hardening-r3` (Round 3):** `Stamp::first_mono` and `Stamp::inherit_observation` settle future-mtime files after `RACY` monotonic duration while preserving re-reads on edits, wall-clock catch-up, and clock step-backs (`project/files.rs`, `project/mod.rs`). | linux-test-portability (Round 2) | ~~lucisv_mcp (`project/files.rs`)~~ done |
| 55 | `crates/lucisv/tests/cli.rs:2149` (`a_stdin_buffer_reads_the_rule_options_too`) asserts only an empty stdout, no exit code (TODO §70) | linux-test-portability (Round 2) | crates/lucisv (tests) |
| ~~55~~ | ~~`crates/lucisv/tests/cli.rs:2149` (`a_stdin_buffer_reads_the_rule_options_too`) asserts only an empty stdout, no exit code (TODO §70)~~ — **closed 2026-11-26 by `cli-path-r5` (Round 5A):** strengthened `a_stdin_buffer_reads_the_rule_options_too` with explicit exit-code assertions (`0`/`1`) and added `run_check_stdin` config/`[lint] select/ignore` discovery tests. | linux-test-portability (Round 2) | ~~crates/lucisv (tests)~~ done |
| ~~56~~ | ~~`crates/lucisv_mcp/tests/qa_m3.rs` uses `std::os::unix` with no `cfg`, so `cargo check --all-targets` for Windows fails (tests only; the `cross` gate checks binaries only) (TODO §70)~~ — **closed 2026-11-26 by `mcp-hardening-r3` (Round 3):** added portable `mode_bits` and gated Unix-only symlink/`PermissionsExt` tests in `qa_m3.rs` with `#[cfg(unix)]`; verified `cargo check --target x86_64-pc-windows-gnu --all-targets -p lucisv_mcp`. | linux-test-portability (Round 2) | ~~lucisv_mcp (tests)~~ done |
| ~~57~~ | ~~**Releases are gated on macOS alone**: Linux runs the suite in `ci.yml` but the release does not wait for it, and Windows is compile-checked (`cross`), never executed (TODO §70)~~ — **closed 2026-11-26 by `ci-gates-r4` (Round 4A):** `.gitea/workflows/release.yml` splits into `preflight` (fail-fast tag/manifest/`CHANGELOG.md` check before `gates.sh`) → `linux` (`runs-on: linux-x64`: clippy + guarded `cargo test --workspace`) → `build-and-publish`. (Windows remains cross-compile checked via `cross`.) | linux-test-portability (Round 2) | ~~tools/ + CI (lead)~~ done |
| 58 | **The discovery walk at the start of every scan drains nothing** (25–80 ms on OpenTitan): what is left of the first-colour wait in workspace scope (62–86 ms late open) and the rescan hold (70–159 ms). Wanted: a resumable walk in `state/discover.rs` (it holds `&mut Workspace` throughout `begin_scan`), with its own identical-result proof (TODO §71 wave 7) | viewport-highlight (Handshake request 2) | lucisv_server (`state/discover.rs`) |
+54 -9
View File
@@ -40,11 +40,16 @@ done
[ -x "$lucisv" ] || { echo "no lucisv binary at $lucisv (cargo build --release?)" >&2; exit 2; }
[ -d "$corpus_dir" ] || { echo "no corpus at $corpus_dir (tools/corpus_fetch.sh?)" >&2; exit 2; }
use_json=0
if command -v jq >/dev/null 2>&1; then
use_json=1
fi
# --- per-file classification --------------------------------------------------
# classify FILE LINE MESSAGE -> category name on stdout.
# classify FILE LINE MESSAGE [CATEGORY] -> category name on stdout.
classify() {
file=$1 line=$2 msg=$3
file=$1 line=$2 msg=$3 err_cat=${4:-}
src=
if [ -n "$line" ] && [ "$line" -gt 0 ] 2>/dev/null; then
src=$(sed -n "${line}p" "$file" 2>/dev/null || true)
@@ -56,12 +61,21 @@ classify() {
ctx="$(sed -n "$((line - 1))p" "$file" 2>/dev/null || true) $src"
fi
case $err_cat in
verification-error) echo verification-error; return ;;
esac
case $msg in
*"verification failed"*) echo verification-error; return ;;
esac
case $file in
*.tpl.sv) echo not-verilog; return ;;
esac
if [ "$err_cat" = "lex-error" ]; then
case $ctx in
*"'h\`"*|*"'d\`"*|*"'b\`"*|*"'o\`"*) echo lex-macro-number; return ;;
esac
echo lex-error; return
fi
case $msg in
*"keyword \`interface\`"*|*"keyword \`default\`"*|*"keyword \`clocking\`"*) echo interface; return ;;
*"(found \"virtual\")"*) echo interface; return ;;
@@ -129,7 +143,11 @@ classify() {
check_one() {
file=$1
status=0
out=$("$lucisv" --no-cache --check "$file" 2>&1) || status=$?
if [ "$use_json" -eq 1 ]; then
out=$("$lucisv" --no-cache --check --output-format json "$file" 2>/dev/null) || status=$?
else
out=$("$lucisv" --no-cache --check "$file" 2>&1) || status=$?
fi
case $status in
0|1)
lstatus=0
@@ -142,12 +160,39 @@ check_one() {
esac
;;
2)
msg=$(printf '%s\n' "$out" | grep '^error: ' | head -1)
msg=${msg#error: }
msg=${msg#"$file": }
err_cat=
line=
msg=
if [ "$use_json" -eq 1 ] && [ -n "$out" ]; then
parsed=$(printf '%s\n' "$out" | jq -r '.files[0].error // {} | [(.category // ""), ((.line // "") | tostring), ((.column // "") | tostring), ((.message // "") | gsub("[\t\r\n]"; " "))] | "\(.[0])\n\(.[1])\n\(.[2])\n\(.[3])"' 2>/dev/null || true)
if [ -n "$parsed" ]; then
{
IFS= read -r err_cat
IFS= read -r line
IFS= read -r col
IFS= read -r raw_msg
} <<EOF
$parsed
EOF
case $err_cat in
parse-error) msg="parse error: ${line}:${col}: ${raw_msg}" ;;
lex-error) msg="lex error: ${line}:${col}: ${raw_msg}" ;;
*) msg=$raw_msg ;;
esac
fi
fi
if [ -z "$msg" ]; then
if [ "$use_json" -eq 1 ]; then
out=$("$lucisv" --no-cache --check "$file" 2>&1 || true)
fi
msg=$(printf '%s\n' "$out" | grep '^error: ' | head -1)
msg=${msg#error: }
msg=${msg#"$file": }
msg=$(printf '%s' "$msg" | tr '\t\n' ' ')
line=$(printf '%s' "$msg" | sed -n 's/^[a-z]* error: \([0-9][0-9]*\):.*/\1/p')
fi
msg=$(printf '%s' "$msg" | tr '\t\n' ' ')
line=$(printf '%s' "$msg" | sed -n 's/^[a-z]* error: \([0-9][0-9]*\):.*/\1/p')
cat=$(classify "$file" "${line:-0}" "$msg")
cat=$(classify "$file" "${line:-0}" "$msg" "$err_cat")
printf 'fail\t%s\t%s\t%s\n' "$cat" "$file" "$msg"
;;
*)
@@ -157,7 +202,7 @@ check_one() {
}
export -f classify check_one
export lucisv
export lucisv use_json
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
+79 -17
View File
@@ -32,35 +32,97 @@ done
[ -x "$lucisv" ] || { echo "no lucisv binary at $lucisv (cargo build --release?)" >&2; exit 2; }
[ -d "$corpus_dir" ] || { echo "no corpus at $corpus_dir (tools/corpus_fetch.sh?)" >&2; exit 2; }
use_json=0
if command -v jq >/dev/null 2>&1; then
use_json=1
fi
# Classify exit-2 text output into `outcome` and `msg`.
classify_text_error() {
text=$1
file=$2
msg=$(printf '%s\n' "$text" | grep '^error: ' | head -1)
msg=${msg#error: }
msg=${msg#"$file": }
case $msg in
*"verification failed"*) outcome=verification-error ;;
"parse error:"*|"lex error:"*) outcome=parse-error ;;
*) outcome=other-error ;;
esac
}
# Classify one file. lucisv --check exit codes (frozen contract, see README):
# 0 clean, 1 would reformat, 2 error. Anything else is a crash -- a signal
# death (128+n) or an abort the per-file catch_unwind could not contain.
check_one() {
file=$1
status=0
out=$("$lucisv" --check "$file" 2>&1) || status=$?
msg=$(printf '%s\n' "$out" | grep '^error: ' | head -1)
msg=${msg#error: }
msg=${msg#"$file": }
msg=
if [ "$use_json" -eq 1 ]; then
out=$("$lucisv" --check --output-format json "$file" 2>/dev/null) || status=$?
else
out=$("$lucisv" --check "$file" 2>&1) || status=$?
fi
case $status in
0) outcome=ok-unchanged ;;
1) outcome=would-reformat ;;
2)
if [ "$use_json" -eq 1 ] && [ -n "$out" ]; then
parsed=$(printf '%s\n' "$out" | jq -r '.files[0].error // {} | [(.category // ""), ((.line // "") | tostring), ((.column // "") | tostring), ((.message // "") | gsub("[\t\r\n]"; " "))] | "\(.[0])\n\(.[1])\n\(.[2])\n\(.[3])"' 2>/dev/null || true)
if [ -n "$parsed" ]; then
{
IFS= read -r cat
IFS= read -r line
IFS= read -r col
IFS= read -r raw_msg
} <<EOF
$parsed
EOF
case $cat in
verification-error)
outcome=verification-error
msg=$raw_msg
;;
parse-error)
outcome=parse-error
msg="parse error: ${line}:${col}: ${raw_msg}"
;;
lex-error)
outcome=parse-error
msg="lex error: ${line}:${col}: ${raw_msg}"
;;
*)
outcome=other-error
msg=$raw_msg
;;
esac
fi
fi
if [ -z "$msg" ]; then
if [ "$use_json" -eq 1 ]; then
out=$("$lucisv" --check "$file" 2>&1 || true)
fi
classify_text_error "$out" "$file"
fi
;;
*)
if [ "$use_json" -eq 1 ]; then
out=$("$lucisv" --check "$file" 2>&1 || true)
fi
msg=$(printf '%s\n' "$out" | grep '^error: ' | head -1)
msg=${msg#error: }
msg=${msg#"$file": }
outcome=crash
msg="exit status $status ${msg:-(no diagnostic)}"
;;
esac
# A diagnostic can embed raw source text (e.g. a verification-error's
# comment payload) that itself contains a literal tab or newline -- see
# QA log 2026-08-19. Squash those before the TSV write below, or a stray
# tab silently splits this row into 4+ fields for every downstream
# awk -F'\t'/cut -f consumer.
msg=$(printf '%s' "$msg" | tr '\t\n' ' ')
case $status in
0) outcome=ok-unchanged; msg= ;;
1) outcome=would-reformat; msg= ;;
2)
case $msg in
*"verification failed"*) outcome=verification-error ;;
"parse error:"*|"lex error:"*) outcome=parse-error ;;
*) outcome=other-error ;;
esac
;;
*) outcome=crash; msg="exit status $status ${msg:-(no diagnostic)}" ;;
esac
printf '%s\t%s\t%s\n' "$outcome" "$file" "$msg"
}