Files
lucisv/crates/lucisv_server/src/auto_style.rs
T
Guoliang ChenandClaude Mythos 5.2 80017a59f2
release / build-and-publish (push) Successful in 5m22s
Release 0.65.5: named formatting styles
TODO §71.5. One setting picks a house layout — [format] style in
lucisv.toml, --style, the lucisv.format.style drop-down, the server and MCP:
lucisv (default), google, lowrisc, ansi, microsoft, nxp, and auto. Seven
layout rules (indent, width, begin placement, else placement, else after a
labelled end, one-per-line lists, list indent, alignment), one row per style
in one table in crates/vlog_formatter/src/style.rs. google and lowrisc follow
those published guides; ansi, microsoft and nxp are lucisv's guesses and say
so. auto formats with each preset and keeps the result that changes the
fewest lines (crates/vlog_formatter/src/auto.rs); the language server
remembers each document's preset (lucisv_server/src/auto_style.rs) so
selection and on-type formatting do not repeat the search. The style is part
of the format cache key.

Proof: default output byte-identical to 0.65.4 on 4 921 files (corpus +
OpenTitan hw) against an independently rebuilt 0.65.4; every style formatted
three times over the same files with no verification error, crash, token or
comment difference (independent lexer) or second-run change. verify.rs is
untouched.

Dev (three rounds), QA (two rounds, pass with findings) and lead review are
in docs/features/format-styles/README.md. Three one-line calls were added to
lucisv_server/src/server/notification.rs for the memory's invalidation.
TODO.md files the pre-existing bugs QA met on the way.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.5) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree; vlog_formatter 376/0,
lucisv_server 1996/0, corpus 814/6.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 07:03:20 -08:00

405 lines
17 KiB
Rust

//! The preset `style = "auto"` last settled on, per document.
//!
//! Under `auto`, every formatting request needs a concrete preset, and
//! finding one means formatting the whole buffer once per preset. That is
//! fine for a whole-document format, which formats the whole buffer anyway,
//! but not for an on-type `;` or a selection, which would pay it on every
//! keystroke — and on a buffer that does not parse (exactly when on-type
//! runs), no preset can be found at all.
//!
//! So a whole-document format remembers the preset it used, and the range,
//! selection and on-type requests reuse it. Without a memory they resolve
//! once from the buffer — when it parses — and remember that. Without a
//! memory and without a parse they lay out in the default preset's layout,
//! as the formatter itself does. The memory is a small most-recent list.
//!
//! A remembered preset is only right while the buffer is still the text it
//! was resolved from, edited by hand. So it is **forgotten** whenever that
//! may no longer be true: the document is opened, closed, renamed or deleted;
//! it is formatted or laid out under a named style; and — for every document
//! — whenever the settings change or a `lucisv.toml` change is seen.
//! Forgetting costs one search on the next request; remembering wrongly would
//! lay the file out in a preset it no longer uses.
//!
//! A change that replaces the **whole** buffer (a reload from disk, an
//! external formatter, or every change of a full-sync client) marks the
//! entry *replaced* rather than dropping it: the next request resolves
//! afresh from the new text, and only if that text does not parse — so there
//! is nothing to resolve from — does it fall back to the old preset, which is
//! still a better guess than the default layout. A full-sync client's every
//! keystroke is such a change, and a half-typed buffer is exactly when
//! on-type runs; dropping the entry there would lose the file's preset at the
//! moment the memory exists for.
//! See `docs/features/format-styles/README.md`.
use std::collections::VecDeque;
use lsp_server::Notification;
use lsp_types::notification::{
DidChangeWatchedFiles, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
DidRenameFiles, Notification as _,
};
use lsp_types::{
DeleteFilesParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, RenameFilesParams, TextDocumentContentChangeEvent, TextEdit, Uri,
};
use vlog_formatter::{format_auto, style, Config, Style};
use crate::format;
use crate::state::Document;
/// How many documents' presets are remembered.
const CAPACITY: usize = 64;
/// The presets of the most recently formatted documents, newest last.
#[derive(Default)]
pub struct AutoStyles {
recent: VecDeque<Entry>,
}
/// One remembered document.
struct Entry {
uri: Uri,
preset: Style,
/// A change replaced the whole buffer since `preset` was resolved, so it
/// is only a fallback: resolve again when the buffer parses.
replaced: bool,
}
impl AutoStyles {
/// Format a whole buffer. Under `auto` this resolves afresh and
/// remembers the preset it used; under a named style it is
/// [`format::formatting`].
pub fn format_document(
&mut self,
uri: &Uri,
doc: &Document,
config: &Config,
) -> Result<Option<TextEdit>, String> {
if !config.auto_style {
// Formatted under a named style, the buffer may now be in it.
self.forget(uri);
return format::formatting(doc, config);
}
let (formatted, preset) = format_auto(&doc.text, config).map_err(|e| e.to_string())?;
self.remember(uri, preset);
Ok(format::whole_document_edit(doc, formatted))
}
/// `config` made concrete for a range, selection or on-type request on
/// `doc`: unchanged under a named style; under `auto`, the remembered
/// preset, else the one the buffer resolves to (then remembered), else —
/// the buffer does not parse — the default preset's layout.
pub fn concrete(&mut self, uri: &Uri, doc: &Document, config: Config) -> Config {
if !config.auto_style {
self.forget(uri);
return config;
}
let held = self.recall(uri);
let preset = match held {
Some((preset, false)) => preset,
// Nothing trustworthy held: resolve from the buffer when it
// parses; otherwise the old preset if there is one, else the
// default layout. A fallback is never stored as fresh.
_ => match format_auto(&doc.text, &config) {
Ok((_, preset)) => {
self.remember(uri, preset);
preset
}
Err(_) => held.map_or(style::LUCISV, |(preset, _)| preset),
},
};
Config { style: preset, auto_style: false, ..config }
}
/// Whether nothing is remembered yet.
#[cfg(test)]
pub fn is_empty(&self) -> bool {
self.recent.is_empty()
}
/// Forget what a notification may have made stale: the document a
/// `didOpen`/`didClose` names, the old and new names of a renamed file,
/// a deleted file, and every document when a watched-file event names a
/// `lucisv.toml` or `.lucisv.toml`. Anything else is ignored.
pub fn notice(&mut self, notification: &Notification) {
let params = || notification.params.clone();
match notification.method.as_str() {
DidOpenTextDocument::METHOD => {
if let Ok(p) = serde_json::from_value::<DidOpenTextDocumentParams>(params()) {
self.forget(&p.text_document.uri);
}
}
DidCloseTextDocument::METHOD => {
if let Ok(p) = serde_json::from_value::<DidCloseTextDocumentParams>(params()) {
self.forget(&p.text_document.uri);
}
}
DidRenameFiles::METHOD => {
if let Ok(p) = serde_json::from_value::<RenameFilesParams>(params()) {
self.forget_named(p.files.iter().flat_map(|f| [&f.old_uri, &f.new_uri]));
}
}
DidDeleteFiles::METHOD => {
if let Ok(p) = serde_json::from_value::<DeleteFilesParams>(params()) {
self.forget_named(p.files.iter().map(|f| &f.uri));
}
}
DidChangeWatchedFiles::METHOD => {
if let Ok(p) = serde_json::from_value::<DidChangeWatchedFilesParams>(params()) {
if p.changes.iter().any(|c| names_a_config(c.uri.as_str())) {
self.forget_all();
}
}
}
_ => {}
}
}
/// Mark `uri`'s entry replaced when a `didChange` replaced its whole
/// text: a change with no range (full sync), or one that starts at the
/// top and leaves nothing of the old text after it — `result` is exactly
/// its text.
pub fn changed(&mut self, uri: &Uri, changes: &[TextDocumentContentChangeEvent], result: &str) {
let rangeless = changes.iter().any(|c| c.range.is_none());
let from_the_top = changes.last().is_some_and(|c| {
c.range.is_some_and(|r| r.start.line == 0 && r.start.character == 0) && c.text == result
});
if rangeless || from_the_top {
if let Some(entry) = self.recent.iter_mut().find(|e| e.uri == *uri) {
entry.replaced = true;
}
}
}
/// Forget every document: the settings, or a `lucisv.toml`, changed.
pub fn forget_all(&mut self) {
self.recent.clear();
}
fn forget(&mut self, uri: &Uri) {
self.recent.retain(|e| e.uri != *uri);
}
fn forget_named<'a>(&mut self, uris: impl Iterator<Item = &'a String>) {
for uri in uris {
self.recent.retain(|e| e.uri.as_str() != uri);
}
}
/// The remembered preset, and whether it has been marked replaced.
fn recall(&self, uri: &Uri) -> Option<(Style, bool)> {
self.recent.iter().find(|e| e.uri == *uri).map(|e| (e.preset, e.replaced))
}
fn remember(&mut self, uri: &Uri, preset: Style) {
self.forget(uri);
if self.recent.len() == CAPACITY {
self.recent.pop_front();
}
self.recent.push_back(Entry { uri: uri.clone(), preset, replaced: false });
}
}
/// Whether a URI names a config file: `lucisv.toml` or `.lucisv.toml`.
fn names_a_config(uri: &str) -> bool {
let name = uri.rsplit('/').next().unwrap_or(uri);
lucisv_core::config::NAMES.contains(&name)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::Workspace;
use std::str::FromStr;
/// A google-formatted module: one port per line at a 4-space list indent.
const GOOGLE: &str = "\
module m (
input logic a,
output logic b
);
sub u_sub (
.a(a),
.b(b)
);
endmodule
";
fn open(text: &str) -> (Workspace, Uri) {
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
(ws, uri)
}
fn auto() -> Config {
Config::named("auto").expect("auto")
}
#[test]
fn a_whole_document_format_remembers_the_preset_it_used() {
let (ws, uri) = open(GOOGLE);
let mut styles = AutoStyles::default();
let doc = ws.document(&uri).expect("open");
assert_eq!(styles.format_document(&uri, doc, &auto()), Ok(None), "already formatted");
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)));
let concrete = styles.concrete(&uri, doc, auto());
assert_eq!((concrete.style, concrete.auto_style), (style::GOOGLE, false));
}
#[test]
fn a_named_style_is_left_alone_and_nothing_is_remembered() {
let (ws, uri) = open(GOOGLE);
let mut styles = AutoStyles::default();
let doc = ws.document(&uri).expect("open");
let ansi = Config::styled(style::ANSI);
assert_eq!(styles.concrete(&uri, doc, ansi.clone()).style, style::ANSI);
assert!(styles.format_document(&uri, doc, &ansi).is_ok());
assert_eq!(styles.recall(&uri), None);
}
/// The memory is what lets a half-typed buffer keep its file's preset:
/// without it, a buffer that does not parse gets the default's layout.
#[test]
fn a_buffer_that_does_not_parse_uses_the_remembered_preset() {
let broken = GOOGLE.replace("endmodule", " assign x = ;\nendmodule");
let (ws, uri) = open(&broken);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "no memory, no parse");
assert_eq!(styles.recall(&uri), None, "and a fallback is not remembered");
styles.remember(&uri, style::GOOGLE);
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE);
}
#[test]
fn without_a_memory_a_buffer_that_parses_resolves_once() {
let (ws, uri) = open(GOOGLE);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE);
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)), "resolved, then remembered");
}
#[test]
fn the_memory_is_bounded_and_keeps_the_most_recent() {
let mut styles = AutoStyles::default();
let uri = |n: usize| Uri::from_str(&format!("file:///rtl/m{n}.sv")).expect("uri");
for n in 0..CAPACITY + 10 {
styles.remember(&uri(n), style::NXP);
}
assert_eq!(styles.recent.len(), CAPACITY);
assert_eq!(styles.recall(&uri(0)), None, "the oldest is forgotten");
assert_eq!(styles.recall(&uri(CAPACITY + 9)), Some((style::NXP, false)));
// Remembering again moves a document to the back and replaces its preset.
styles.remember(&uri(10), style::ANSI);
styles.remember(&uri(10), style::GOOGLE);
assert_eq!(styles.recall(&uri(10)), Some((style::GOOGLE, false)));
assert_eq!(styles.recent.len(), CAPACITY);
}
fn notification(method: &str, params: serde_json::Value) -> Notification {
Notification { method: method.to_string(), params }
}
#[test]
fn open_close_rename_and_delete_forget_the_document() {
let mut styles = AutoStyles::default();
let (a, b) = (
Uri::from_str("file:///rtl/a.sv").expect("uri"),
Uri::from_str("file:///rtl/b.sv").expect("uri"),
);
let doc = |uri: &Uri| {
serde_json::json!({ "textDocument": {
"uri": uri, "languageId": "systemverilog", "version": 1, "text": "" } })
};
for method in [DidOpenTextDocument::METHOD, DidCloseTextDocument::METHOD] {
styles.remember(&a, style::GOOGLE);
styles.notice(&notification(method, doc(&a)));
assert_eq!(styles.recall(&a), None, "{method}");
}
styles.remember(&a, style::GOOGLE);
styles.remember(&b, style::NXP);
styles.notice(&notification(
DidRenameFiles::METHOD,
serde_json::json!({ "files": [{ "oldUri": a.as_str(), "newUri": b.as_str() }] }),
));
assert!(styles.is_empty(), "both names of a renamed file are forgotten");
styles.remember(&a, style::GOOGLE);
styles.notice(&notification(
DidDeleteFiles::METHOD,
serde_json::json!({ "files": [{ "uri": a.as_str() }] }),
));
assert_eq!(styles.recall(&a), None);
}
#[test]
fn a_config_file_change_or_a_settings_change_forgets_everything() {
let mut styles = AutoStyles::default();
let a = Uri::from_str("file:///rtl/a.sv").expect("uri");
let watched = |name: &str| {
notification(
DidChangeWatchedFiles::METHOD,
serde_json::json!({ "changes": [{ "uri": format!("file:///rtl/{name}"), "type": 2 }] }),
)
};
styles.remember(&a, style::GOOGLE);
styles.notice(&watched("other.sv"));
assert!(!styles.is_empty(), "a source file changing on disk says nothing about presets");
for name in ["lucisv.toml", ".lucisv.toml"] {
styles.remember(&a, style::GOOGLE);
styles.notice(&watched(name));
assert!(styles.is_empty(), "{name}");
}
styles.remember(&a, style::GOOGLE);
styles.forget_all();
assert!(styles.is_empty());
}
/// A whole-buffer change makes the entry a fallback: the next request
/// resolves from the new text if it parses, and keeps the old preset
/// only if it does not. A partial edit leaves the entry alone.
#[test]
fn a_whole_buffer_replacement_resolves_again_when_it_can() {
let lucisv =
"module m (input logic a, output logic b);\n sub u_sub (.a(a), .b(b));\nendmodule\n";
let (ws, uri) = open(lucisv);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
styles.remember(&uri, style::GOOGLE);
let edit: TextDocumentContentChangeEvent =
serde_json::from_value(serde_json::json!({
"range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 2 } },
"text": " " })).expect("change");
styles.changed(&uri, &[edit], lucisv);
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE, "a partial edit");
let whole: TextDocumentContentChangeEvent =
serde_json::from_value(serde_json::json!({ "text": lucisv })).expect("change");
styles.changed(&uri, std::slice::from_ref(&whole), lucisv);
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, true)));
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "resolved afresh");
assert_eq!(styles.recall(&uri), Some((style::LUCISV, false)));
// A full range from the top counts as a whole replacement too.
let ranged: TextDocumentContentChangeEvent =
serde_json::from_value(serde_json::json!({
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 3, "character": 0 } },
"text": lucisv })).expect("change");
styles.changed(&uri, &[ranged], lucisv);
assert_eq!(styles.recall(&uri), Some((style::LUCISV, true)));
}
#[test]
fn a_named_style_request_forgets_the_document() {
let (ws, uri) = open(GOOGLE);
let doc = ws.document(&uri).expect("open");
let mut styles = AutoStyles::default();
styles.remember(&uri, style::GOOGLE);
styles.concrete(&uri, doc, Config::styled(style::LUCISV));
assert_eq!(styles.recall(&uri), None, "a range under a named style");
styles.remember(&uri, style::GOOGLE);
let _ = styles.format_document(&uri, doc, &Config::styled(style::LUCISV));
assert_eq!(styles.recall(&uri), None, "a whole-document format under a named style");
}
}