//! Formatting rules: AST → Doc. //! //! Style follows Verible's defaults: 2-space indent, 100-column lines, //! one-element-per-line port/connection lists when a construct does not fit //! on a single line, cuddled `begin`/`end`. //! //! The rules are one `Fmt` whose methods are spread over the sibling //! modules by grammar domain — `item`, `module`, `instance`, `decl`, //! `routine`, `class`, `cover`, `sva`, `stmt`, `expr` — on top of the //! shared machinery they all print through — `comment`, `verbatim`, //! `phrase`, `list`. This file holds what the crate exports (`Config`, //! `FormatError`, `format_source`, `format_range`), the `Fmt` state, and //! the name helpers every module writes an identifier through. mod class; mod comment; mod cover; mod decl; mod expr; mod instance; mod item; mod list; mod module; mod phrase; mod routine; mod stmt; mod sva; mod verbatim; use crate::doc::{text, Doc}; use crate::fence::{self, Region}; use crate::printer::Printer; use crate::range::{self, Split}; use crate::verify::{verify_convergence, verify_equivalence, VerificationError}; use vlog_parser::ast::*; #[derive(Debug, Clone)] pub struct Config { pub max_width: usize, pub indent_width: usize, } impl Default for Config { fn default() -> Self { Config { max_width: 100, indent_width: 2 } } } /// Everything that can stop the formatter from producing output. #[derive(Debug)] pub enum FormatError { /// The input could not be lexed or parsed. Source(vlog_parser::Error), /// A safety check failed; the formatted text was discarded. Verification(VerificationError), } impl std::fmt::Display for FormatError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { FormatError::Source(e) => write!(f, "{e}"), FormatError::Verification(e) => write!(f, "{e}"), } } } impl std::error::Error for FormatError {} impl From for FormatError { fn from(e: vlog_parser::Error) -> Self { FormatError::Source(e) } } impl From for FormatError { fn from(e: VerificationError) -> Self { FormatError::Verification(e) } } /// Format `source`, verifying the result before handing it back. /// /// The output is only returned if it re-lexes to the same token stream as the /// input (comments included) and formatting it again is a fixed point; /// otherwise the caller gets an error and must leave the original text alone. /// /// Parses `source` (twice, for verification), so call this only on a thread /// with at least `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one /// lets sufficiently nested input abort the process instead of returning /// `Err` (see `docs/features/recursion-limit/README.md`). pub fn format_source(source: &str, config: &Config) -> Result { 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)?; Ok(output) } /// Format only the constructs intersecting `lines`, emitting every other byte /// exactly as it was written. /// /// The safety net is the same one and it still runs over the *whole* output: /// the spliced bytes are source text, the laid-out islands are ordinary /// formatter output, and both checks are global. Convergence is checked by /// replaying the same per-item decisions against the output — see /// `docs/features/range-formatting/README.md`. /// /// Same stack requirement as [`format_source`]: needs a thread with at least /// `vlog_parser::PARSE_STACK_SIZE` of stack. pub fn format_range( source: &str, config: &Config, lines: &range::LineRanges, ) -> Result { 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 again = format_selected(&output, config, &selection).map_err(VerificationError::Reparse)?; verify_convergence(&output, &again)?; Ok(output) } /// A single unverified formatting pass: parse, lay out, print. fn format_once(source: &str, config: &Config) -> Result { 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)) } /// The same pass, restricted to the units `selection` picked out. fn format_selected( source: &str, config: &Config, selection: &range::Selection, ) -> Result { 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)) } /// Lay the file out and print it, ending in exactly one newline. fn render(fmt: &Fmt, file: &SourceFile, config: &Config) -> String { let doc = fmt.file(file); let printer = Printer { max_width: config.max_width, indent_width: config.indent_width }; let mut out = printer.print(&doc); // Normalize trailing whitespace: exactly one final newline. while out.ends_with('\n') || out.ends_with(' ') { out.pop(); } out.push('\n'); out } struct Fmt<'a> { cfg: &'a Config, /// The text the AST was parsed from — what `// verilog_format: off` /// regions and `--lines` runs are spliced out of. 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, /// Scope-bearing items a range run descends into. Empty for a whole-file /// run. splits: Vec, } /// A name, plus the space that terminates it when it is an escaped identifier. /// /// An escaped identifier runs from its `\` to the next **whitespace** /// character and to nothing else (IEEE 1800-2017 §5.6.1), so `\my-signal;` /// lexes as one identifier that swallows the `;`, and `.\my-port(x)` as one /// that swallows the rest of the line. Every name the formatter writes goes /// through here (or through [`name_doc`], its `Doc` twin): declarators, /// ANSI and non-ANSI ports, parameters and their aligned cells, type names, /// typedef/enum/genvar/`let` names, module, package, class, function, task, /// modport and clocking names, instance and module-instance names, port /// connections and named call arguments, `extends`, scopes, hierarchical /// members, tf arguments, block/fork/statement labels, every `end : label`, /// `disable`, and the `join_names`/`join_paths` lists. The audit that built /// that list is a grep of `text(` and `format!(` over `format/`; a site that /// grows a name later belongs on it. /// /// The space is unconditional. Where the layout already writes a separator /// the output carries two (`logic \a = 1;`) — legal, a fixed point under /// re-formatting, and cheaper than a second rule about what comes next. fn named(s: &str) -> String { if ends_escaped(s) { format!("{s} ") } else { s.to_string() } } /// [`named`] as a `Doc`. fn name_doc(s: &str) -> Doc { text(named(s)) } /// Whether `s` ends *inside* an escaped identifier, and so cannot be followed /// directly by punctuation. /// /// Whitespace is the only terminator, so the question is exactly whether a /// `\` survives in the run of characters after the last whitespace — which /// also answers it for the composites the AST hands over already joined /// (`a.\b`, `pkg::\x`). Conservative by construction: a false positive /// writes one harmless extra space. `vlog_refactor::instantiate` carries the /// same two-line rule for the skeletons it splices. fn ends_escaped(s: &str) -> bool { s.rsplit(char::is_whitespace).next().unwrap_or(s).contains('\\') } /// A comma-separated list of names, as the source wrote them. The parser /// keeps each name's byte range alongside its text, so the joined spelling is /// rebuilt here rather than stored. fn join_names(names: &[Name]) -> String { names.iter().map(|n| named(&n.text)).collect::>().join(", ") } /// The same for a list of `pkg::item` import paths. fn join_paths(paths: &[ImportPath]) -> String { paths .iter() .map(|p| format!("{}::{}", named(&p.pkg.text), named(&p.item.text))) .collect::>() .join(", ") } /// Offset of the first byte at or after `from` that is neither whitespace nor /// part of a comment, or `None` if the text ends first. /// /// Used to ask what a node is followed by in the source — a `)` that closes /// the header it sits in, the optional `:` of a `default` case label — when /// the AST does not record it. fn skip_trivia(src: &str, from: usize) -> Option { let bytes = src.as_bytes(); let mut i = from; while i < bytes.len() { match bytes[i] { b'/' if bytes.get(i + 1) == Some(&b'/') => { i += 2; while i < bytes.len() && bytes[i] != b'\n' { i += 1; } } b'/' if bytes.get(i + 1) == Some(&b'*') => { i += 2; while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) { i += 1; } i = (i + 2).min(bytes.len()); } c if c.is_ascii_whitespace() => i += 1, _ => return Some(i), } } None }