Files
lucisv/crates/lucisv_server/src/format.rs
T
Guoliang ChenandClaude Mythos 5.2 aa2259bfe1 Round 12: pure-move splits and hygiene
Splits resolve.rs, parser/item.rs, parser/instance.rs, format/stmt.rs and
lexer.rs (really 771 lines); moves 23 inline test modules of lucisv_server
to their own files; reasons on all 12 bare #[ignore]; the giant-line
references test times the real request; sites.py default root.
Output over 4,046 OpenTitan files byte-identical to a479faf.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 20:39:56 -08:00

307 lines
14 KiB
Rust

// Author: Guoliang Chen, a Senior Digital Design Engineer
//! `textDocument/formatting`, `textDocument/rangeFormatting` and
//! `textDocument/rangesFormatting`.
//!
//! The formatter's contract is all-or-nothing (CLAUDE.md invariant #1), and
//! these handlers keep it: either one whole-document edit built from verified
//! output, or no edit at all and an error for the user to read. That holds for
//! the range requests too — their output is verified over the whole buffer,
//! and what makes a request a *range* format is which constructs it laid out,
//! not which bytes it was allowed to replace. The range requests go through
//! `format_selection`: the smallest run of sibling items or statements the
//! selection covers, laid out at the indentation it was written at — see
//! `docs/features/selection-formatting/README.md`.
use std::path::Path;
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
use lucisv_core::config::{Discovery, FileConfig};
use vlog_formatter::{
format_selection, format_source, style, Alignment, Config, LineRanges, ListIndent, Placement,
PortLists, Style, StyleOverrides,
};
use crate::settings::ClientSettings;
use crate::state::Document;
/// Indent widths a client may ask for. The same 1..8 range `lucisv.toml`'s own
/// `indent` key allows, so the two agree.
const INDENT_RANGE: std::ops::RangeInclusive<u32> = 1..=8;
/// What to format a buffer with, and the config problem to tell the user
/// about. The two are separate because a broken `lucisv.toml` must not stop the
/// buffer from being formatted.
pub struct Settings {
/// The settings to format with — the fallback defaults when `problem` is
/// set.
pub config: Config,
/// The `lucisv.toml` error governing this buffer, if there is one.
pub problem: Option<String>,
}
/// Resolve the settings governing a buffer.
///
/// Precedence, highest first:
///
/// 1. **`lucisv.toml`** — a checked-in config is the project speaking, and it
/// must stay authoritative or format-on-save would disagree with CI's
/// `lucisv --check`. That divergence is the exact thing lifting the config
/// into `lucisv_core` exists to remove.
/// 2. **The client's `lucisv.*` settings** (`settings.rs`) — typed on purpose
/// into an editor's settings UI, so more deliberate than a tab size, but
/// it is one user's editor and the repository outranks it.
/// 3. **`FormattingOptions::tab_size`** — sent on every request whether or
/// not the user ever chose it; it is the editor's own default, or its
/// guess from the file, so it is the weakest thing that is still a signal.
/// This is *not* the CLI's flag-beats-config order, and deliberately so.
/// 4. **The built-in default.**
///
/// Each rung applies only where every rung above it is silent, so a project
/// with no `lucisv.toml` and no `lucisv.*` settings behaves exactly as it did
/// before either existed.
///
/// **The style** (`[format] style`, `lucisv.format.style`) climbs rungs 1, 2
/// and 4 first, and supplies the indent and width the other keys then
/// overwrite. A style that was chosen on rung 1 or 2 also outranks rung 3:
/// `tabSize` is sent whether or not anyone chose it, and the editor's own
/// default of 4 silently undoing `google`'s 2 is not what choosing a style
/// asked for. With no style chosen — or `lucisv`, which is what VS Code sends
/// when nobody touched the drop-down, and which means exactly "what lucisv
/// always did", or `auto`, which chooses a layout but no size — rung 3
/// behaves exactly as it always has.
pub fn settings_for(
doc: &Document,
client: &ClientSettings,
options: &FormattingOptions,
) -> Settings {
let (file, problem) = discover(doc.path.as_deref());
Settings { config: config_from(&file, client, options), problem }
}
/// Resolve the settings governing a buffer for a request that carries no
/// `FormattingOptions`.
///
/// `textDocument/willSaveWaitUntil` has no options field at all — the protocol
/// simply does not carry one there. So the ladder `settings_for` documents
/// runs with rung 3 missing, which is the same thing `indent_width` does for a
/// lint fix: `lucisv.toml` > the pushed `lucisv.*` settings > the built-in
/// default. Spelled as hard tabs and a zero width because `config_from` takes
/// neither, so nothing is guessed on the user's behalf.
pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings) -> Settings {
let none = FormattingOptions { tab_size: 0, insert_spaces: false, ..Default::default() };
settings_for(doc, client, &none)
}
/// Format a buffer.
///
/// `Ok(None)` means "nothing to do" — the buffer is already formatted, and an
/// edit that changes nothing still moves the cursor in some editors. `Err`
/// carries the formatter's own message; the caller surfaces it, and must not
/// invent an edit from it.
pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, String> {
let formatted = format_source(&doc.text, config).map_err(|e| e.to_string())?;
Ok(whole_document_edit(doc, formatted))
}
/// The one edit that turns `doc` into `formatted`, or none when they are
/// already the same text.
pub fn whole_document_edit(doc: &Document, formatted: String) -> Option<TextEdit> {
if formatted == doc.text {
return None;
}
Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted })
}
/// `textDocument/rangesFormatting`, the LSP 3.18 multi-range request.
///
/// Spelled out here because `lsp-types` 0.97 predates it — the same reason
/// `pairs::ScopePairsParams` is hand-rolled. See
/// `docs/features/lsp-318-extras/README.md`.
pub const RANGES_FORMATTING: &str = "textDocument/rangesFormatting";
/// `textDocument/rangesFormatting` params: one document, `n` ranges, one set
/// of options.
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RangesFormattingParams {
pub text_document: TextDocumentIdentifier,
pub ranges: Vec<Range>,
pub options: FormattingOptions,
}
/// Format the constructs a selection reaches, and nothing else.
///
/// The one-range case of [`ranges_formatting`], which is where the whole
/// answer lives — an `n`-range request is this request with `n` line spans.
pub fn range_formatting(
doc: &Document,
config: &Config,
range: Range,
) -> Result<Option<TextEdit>, String> {
ranges_formatting(doc, config, std::slice::from_ref(&range))
}
/// Format the constructs any of several selections reach, and nothing else.
///
/// The ranges are a *set*: they are sorted and merged by `LineRanges::new`
/// before the engine sees them, so overlapping, adjacent, repeated and
/// unsorted input from the client all reach the same answer. Each merged span
/// selects its own target (targets that overlap are re-selected from the hull
/// of their spans), but no range is formatted on its own — one
/// `format_selection` call lays out and verifies them all, which is what keeps
/// the all-or-nothing contract (CLAUDE.md invariant #1) whole rather than
/// making it a promise per range.
///
/// The reply is still one whole-document edit: the engine's contract is
/// all-or-nothing over the file, and a partial run's output differs from the
/// buffer only where it decided to differ. An empty range list is not an
/// error — it is an ask for nothing, answered with no edit.
pub fn ranges_formatting(
doc: &Document,
config: &Config,
ranges: &[Range],
) -> Result<Option<TextEdit>, String> {
if ranges.is_empty() {
return Ok(None);
}
let lines = LineRanges::new(ranges.iter().copied().map(lines_of))?;
let formatted = format_selection(&doc.text, config, &lines).map_err(|e| e.to_string())?;
if formatted == doc.text {
return Ok(None);
}
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
}
/// The 1-based inclusive line span an LSP range names.
///
/// The protocol's `Range` is a half-open span of UTF-16 positions; the engine
/// wants lines, so only the line numbers survive the conversion — which
/// sidesteps the UTF-16 column question rather than solving it again. An end
/// position at character 0 still names its line — an editor's "select these
/// three lines" ends at the start of the fourth — so a range that stops at a
/// line's very beginning does not drag that line in unless it is also where
/// the range started.
///
/// One conversion, shared by both range requests: a second spelling of this
/// rule would be a second thing to get wrong.
fn lines_of(range: Range) -> (u32, u32) {
let first = range.start.line.saturating_add(1);
// An end at character 0 of a later line is the start of that line, not
// any of its content.
let ends_before_its_line = range.end.character == 0 && range.end.line > range.start.line;
let last = if ends_before_its_line { range.end.line } else { range.end.line.saturating_add(1) };
(first, last.max(first))
}
/// The indent width governing a buffer, for a lint fix that has to write
/// spaces where a tab was.
///
/// A `textDocument/codeAction` request carries no `FormattingOptions`, so there
/// is no client `tabSize` to consider here — the precedence is the same ladder
/// `settings_for` documents with rung 3 missing: `lucisv.toml` > `lucisv.indent` >
/// the built-in default. A broken config is silent on this path: the
/// formatting path is where the user is told about it, and warning from a
/// lightbulb the editor requests on every cursor move would be noise.
pub fn indent_width(path: Option<&Path>, client: &ClientSettings) -> usize {
let (file, _problem) = discover(path);
file.indent
.or(client.indent)
.unwrap_or(chosen_style(&file, client).unwrap_or(style::LUCISV).indent)
}
/// The preset a project or a user picked for this buffer, `lucisv.toml`
/// first; `None` when neither did, or when the pick is `auto`, which names
/// no preset and so no indent.
fn chosen_style(file: &FileConfig, client: &ClientSettings) -> Option<Style> {
file.format_style.or(client.style).and_then(style::preset)
}
/// The config file governing `path`, by the CLI's own discovery rule, or the
/// error that stopped it from being read. A buffer with no path (`untitled:`)
/// has no directory to search from, so it gets no config.
fn discover(path: Option<&Path>) -> (FileConfig, Option<String>) {
let Some(path) = path else { return (FileConfig::default(), None) };
// A fresh `Discovery` per request, so a `lucisv.toml` edited while the
// server runs takes effect at the next format. One file read on an
// explicit, user-initiated request is cheaper than any cache invalidation
// scheme that could be wrong.
match Discovery::new(true).for_file(path) {
Ok(file) => (file, None),
Err(problem) => (FileConfig::default(), Some(problem)),
}
}
/// Fold the config file, the pushed `lucisv.*` settings and the client's tab
/// options into formatter settings, in the precedence `settings_for`
/// documents. Written weakest-first, so the last writer wins.
///
/// The client's `tab_size` is taken only when the request is sane: a client
/// asking for hard tabs, or for a 40-space indent, is asking for something
/// lucisv does not do, and silently honoring half of it is worse than ignoring
/// it. `lucisv.lineLength` has no `FormattingOptions` analog at all — the
/// protocol carries no line-length option — so before it existed there was no
/// way to set a width from an editor without a `lucisv.toml`.
fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingOptions) -> Config {
let named = file.format_style.or(client.style).and_then(Config::named);
// `auto` picks a layout and no size, so it leaves the editor's rung alone
// exactly as "no style" and `lucisv` do.
let editor_rung = chosen_style(file, client).is_none_or(|s| s == style::LUCISV);
let mut config = named.unwrap_or_default();
if editor_rung && options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
config.indent_width = options.tab_size as usize;
}
if let Some(indent) = client.indent {
config.indent_width = indent;
}
if let Some(line_length) = client.line_length {
config.max_width = line_length;
}
if let Some(indent) = file.indent {
config.indent_width = indent;
}
if let Some(line_length) = file.line_length {
config.max_width = line_length;
}
// The `[format]` keys follow the same ladder: the editor's own setting
// first, then `lucisv.toml`, which outranks it.
if let Some(on) = client.uvm_utils_indent {
config.uvm_utils_indent = on;
}
if let Some(on) = file.format_uvm_utils_indent {
config.uvm_utils_indent = on;
}
config.apply_overrides(overrides_from_client(client));
config.apply_overrides(overrides_from_file(file));
config
}
fn overrides_from_client(client: &ClientSettings) -> StyleOverrides {
StyleOverrides {
begin: client.format_begin.and_then(Placement::parse),
else_keyword: client.format_else.and_then(Placement::parse),
else_after_label: client.format_else_after_label.and_then(Placement::parse),
port_lists: client.format_port_lists.and_then(PortLists::parse),
list_indent: client.format_list_indent.and_then(ListIndent::parse),
alignment: client.format_alignment.and_then(Alignment::parse),
connection_align_min: client.format_connection_align_min,
}
}
fn overrides_from_file(file: &FileConfig) -> StyleOverrides {
StyleOverrides {
begin: file.format_begin.and_then(Placement::parse),
else_keyword: file.format_else.and_then(Placement::parse),
else_after_label: file.format_else_after_label.and_then(Placement::parse),
port_lists: file.format_port_lists.and_then(PortLists::parse),
list_indent: file.format_list_indent.and_then(ListIndent::parse),
alignment: file.format_alignment.and_then(Alignment::parse),
connection_align_min: file.format_connection_align_min,
}
}
#[cfg(test)]
mod tests;
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com