From 6a8517902b7547193f88d40b59f0e3fd20102392 Mon Sep 17 00:00:00 2001 From: Davis Vaughan Date: Fri, 20 Dec 2024 13:50:10 -0500 Subject: [PATCH 1/2] Log a warning on parse errors, but don't return an LSP error --- crates/lsp/src/handlers_format.rs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/lsp/src/handlers_format.rs b/crates/lsp/src/handlers_format.rs index c9de94b3..342d3d5f 100644 --- a/crates/lsp/src/handlers_format.rs +++ b/crates/lsp/src/handlers_format.rs @@ -22,6 +22,16 @@ pub(crate) fn document_formatting( ) -> anyhow::Result>> { let doc = state.get_document(¶ms.text_document.uri)?; + if doc.parse.has_errors() { + // Refuse to format in the face of parse errors, but only log a warning + // rather than returning an LSP error, as toast notifications here are distracting. + tracing::warn!( + "Failed to format {uri}. Can't format when there are parse errors.", + uri = params.text_document.uri + ); + return Ok(None); + } + let line_width = LineWidth::try_from(80).map_err(|err| anyhow::anyhow!("{err}"))?; // TODO: Handle FormattingOptions @@ -29,10 +39,6 @@ pub(crate) fn document_formatting( .with_indent_style(IndentStyle::Space) .with_line_width(line_width); - if doc.parse.has_errors() { - return Err(anyhow::anyhow!("Can't format when there are parse errors.")); - } - let formatted = format_node(options.clone(), &doc.parse.syntax())?; let output = formatted.print()?.into_code(); @@ -51,6 +57,16 @@ pub(crate) fn document_range_formatting( ) -> anyhow::Result>> { let doc = state.get_document(¶ms.text_document.uri)?; + if doc.parse.has_errors() { + // Refuse to format in the face of parse errors, but only log a warning + // rather than returning an LSP error, as toast notifications here are distracting. + tracing::warn!( + "Failed to format {uri}. Can't format when there are parse errors.", + uri = params.text_document.uri + ); + return Ok(None); + } + let line_width = LineWidth::try_from(80).map_err(|err| anyhow::anyhow!("{err}"))?; let range = from_proto::text_range(&doc.line_index.index, params.range, doc.line_index.encoding)?; From bea3663e92b91a2f551dc759b118de82f9c03474 Mon Sep 17 00:00:00 2001 From: Davis Vaughan Date: Fri, 20 Dec 2024 13:52:54 -0500 Subject: [PATCH 2/2] Add changelog bullet --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b4f63a6a..c35e049e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ # Development version +- Parse errors in your document no longer trigger an LSP error when you request + document or range formatting (which typically would show up as an annoying + toast notification in your code editor) (#120). # 0.1.1