Replace stale findings with syntax failures
Rust CI vsg-bridge-ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-10-03 21:16:34 +02:00
parent 2f88b3187e
commit 8008534dfd
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
6 changed files with 284 additions and 46 deletions

View File

@ -50,6 +50,7 @@ The automated suite covers:
- LSP initialization, shutdown, synchronization, and diagnostic clearing;
- use of unsaved in-memory text and suppression of stale results;
- JSON schema, metadata, severity, URL, and line-range validation;
- syntax-error location, stale-warning removal, and correction suppression;
- ASCII, Unicode, UTF-16 positions, CRLF, empty lines, and document boundaries;
- missing, failing, stalled, or non-UTF-8 VSG subprocesses;
- formatting, whole-document fixes, scoped fixes, no-op edits, and concurrent

View File

@ -126,6 +126,10 @@ hx path/to/file.vhd
Diagnostics should appear as you edit. Run `:format` to ask the bridge to
format the current in-memory buffer through the same VSG fix-all path used by
`source.fixAll.vsg`. No separate editor formatter command is required.
If VSG encounters a syntax error, the bridge replaces stale style findings with
one error on the reported line and temporarily withholds formatting and
correction actions. Normal diagnostics and actions return after parsing
succeeds again.
Hover a diagnosed line to see the VSG rule, configured severity, correction
phase, fixability, relevant configuration, and available documentation links.

View File

@ -136,7 +136,11 @@ An analysis failure uses the same protocol identity and version:
"source": {"name": "stdin"},
"rules": {},
"diagnostics": [],
"errors": [{"kind": "analysis", "message": "Error while processing stdin"}]
"errors": [{
"kind": "syntax",
"message": "Unexpected token while parsing entity_declaration; expected `end`",
"location": {"line": 1, "column": 1}
}]
}
```
@ -150,10 +154,12 @@ Unknown optional JSON fields are ignored. A declared unsupported schema or
schema version is a compatibility error and is reported prominently. Malformed
JSON, incomplete analysis, missing required fields, invalid line numbers,
dangling rule references, malformed URLs, or inconsistent metadata are
recoverable tool failures: the bridge warns, retains the last published
diagnostics, and remains available for the next document update. One bad
response must never crash the language server or corrupt results from a newer
document version.
recoverable tool failures: the bridge warns, clears stale style findings and
correction actions, and remains available for the next document update. A
located `syntax` error is published as a non-fixable LSP error on the reported
line; other incomplete failures publish an empty set. Complete analysis restores
normal style diagnostics and correction actions. One bad response must never
crash the language server or corrupt results from a newer document version.
## Correction granularity
@ -212,6 +218,8 @@ Correction menus must be cheap: advertise actions from validated in-memory
diagnostics, then invoke VSG only after the client executes the selected
server-owned command. The command applies the resulting versioned workspace
edit through `workspace/applyEdit`.
Formatting and correction actions are withheld whenever analysis of the current
document version is incomplete.
### Experimental individual rule fix

View File

@ -45,6 +45,17 @@ struct VsgError {
kind: String,
/// Human-readable failure detail.
message: String,
/// Best available parser position, using VSG's one-based coordinates.
location: Option<VsgErrorLocation>,
}
/// Source position associated with an incomplete VSG analysis.
#[derive(Debug, Deserialize)]
struct VsgErrorLocation {
/// One-based source line.
line: u32,
/// One-based source column, validated while the bridge publishes a safe line range.
column: Option<u32>,
}
/// Result of parsing one VSG response without confusing failure with "clean".
@ -52,8 +63,13 @@ struct VsgError {
pub(crate) enum DiagnosticResponse {
/// Analysis completed and these diagnostics may replace the previous set.
Complete(Vec<Diagnostic>),
/// Analysis failed or the response was malformed; retain previous results.
Incomplete(String),
/// Analysis failed or the response was malformed; replace stale findings.
Incomplete {
/// Human-readable failure reported to the user.
message: String,
/// A located syntax failure, when VSG supplied a safe source position.
diagnostics: Vec<Diagnostic>,
},
}
/// Identity of the VSG executable that produced a document.
@ -182,43 +198,55 @@ pub(crate) fn parse_diagnostics(output: &str, document_text: &str) -> Result<Dia
let value: Value = match serde_json::from_str(output) {
Ok(value) => value,
Err(_) => {
return Ok(DiagnosticResponse::Incomplete(
"VSG returned malformed diagnostic JSON; previous diagnostics were retained"
.to_owned(),
return Ok(incomplete(
"VSG returned malformed diagnostic JSON".to_owned(),
Vec::new(),
));
}
};
if let Some(reason) = validate_protocol_identity(&value)? {
return Ok(DiagnosticResponse::Incomplete(reason));
return Ok(incomplete(reason, Vec::new()));
}
let document: DiagnosticDocument = match serde_json::from_value(value) {
Ok(document) => document,
Err(_) => {
return Ok(DiagnosticResponse::Incomplete(
"VSG returned an incomplete diagnostic document; previous diagnostics were retained"
.to_owned(),
return Ok(incomplete(
"VSG returned an incomplete diagnostic document".to_owned(),
Vec::new(),
));
}
};
if !document.complete {
let detail = document
let error = document
.errors
.iter()
.find(|error| !error.message.trim().is_empty())
.map(|error| format!("{}: {}", error.kind, error.message))
.unwrap_or_else(|| "VSG diagnostic analysis did not complete".to_owned());
return Ok(DiagnosticResponse::Incomplete(detail));
.map(|error| (format!("{}: {}", error.kind, error.message), error));
let (detail, diagnostics) = match error {
Some((detail, error)) => (
detail,
syntax_diagnostic(error, document_text)
.into_iter()
.collect(),
),
None => (
"VSG diagnostic analysis did not complete".to_owned(),
Vec::new(),
),
};
return Ok(incomplete(detail, diagnostics));
}
if !document.errors.is_empty() {
return Ok(DiagnosticResponse::Incomplete(
"VSG marked a complete diagnostic document with errors; previous diagnostics were retained"
.to_owned(),
return Ok(incomplete(
"VSG marked a complete diagnostic document with errors".to_owned(),
Vec::new(),
));
}
if let Err(error) = validate_document(&document) {
return Ok(DiagnosticResponse::Incomplete(format!(
"VSG returned invalid diagnostic data ({error}); previous diagnostics were retained"
)));
return Ok(incomplete(
format!("VSG returned invalid diagnostic data ({error})"),
Vec::new(),
));
}
let metrics = LineMetrics::new(document_text);
@ -229,9 +257,10 @@ pub(crate) fn parse_diagnostics(output: &str, document_text: &str) -> Result<Dia
.collect::<Result<Vec<_>>>();
match diagnostics {
Ok(diagnostics) => Ok(DiagnosticResponse::Complete(diagnostics)),
Err(error) => Ok(DiagnosticResponse::Incomplete(format!(
"VSG diagnostic conversion failed ({error}); previous diagnostics were retained"
))),
Err(error) => Ok(incomplete(
format!("VSG diagnostic conversion failed ({error})"),
Vec::new(),
)),
}
}
@ -239,8 +268,7 @@ pub(crate) fn parse_diagnostics(output: &str, document_text: &str) -> Result<Dia
fn validate_protocol_identity(value: &Value) -> Result<Option<String>> {
let Some(document) = value.as_object() else {
return Ok(Some(
"VSG diagnostic output was not a JSON object; previous diagnostics were retained"
.to_owned(),
"VSG diagnostic output was not a JSON object".to_owned(),
));
};
@ -248,22 +276,46 @@ fn validate_protocol_identity(value: &Value) -> Result<Option<String>> {
Some(DIAGNOSTIC_SCHEMA) => {}
Some(schema) => bail!("unsupported VSG diagnostic schema: {schema}"),
None => {
return Ok(Some(
"VSG diagnostic output omitted its schema; previous diagnostics were retained"
.to_owned(),
));
return Ok(Some("VSG diagnostic output omitted its schema".to_owned()));
}
}
match document.get("schema_version").and_then(Value::as_u64) {
Some(version) if version == u64::from(DIAGNOSTIC_SCHEMA_VERSION) => Ok(None),
Some(version) => bail!("unsupported VSG diagnostic schema version: {version}"),
None => Ok(Some(
"VSG diagnostic output omitted its schema version; previous diagnostics were retained"
.to_owned(),
"VSG diagnostic output omitted its schema version".to_owned(),
)),
}
}
/// Constructs a recoverable response which replaces, rather than preserves, stale findings.
fn incomplete(message: String, diagnostics: Vec<Diagnostic>) -> DiagnosticResponse {
DiagnosticResponse::Incomplete {
message,
diagnostics,
}
}
/// Converts a structured parser failure into a non-fixable LSP error.
fn syntax_diagnostic(error: &VsgError, document_text: &str) -> Option<Diagnostic> {
if error.kind != "syntax" {
return None;
}
let location = error.location.as_ref()?;
if location.line == 0 || location.column == Some(0) {
return None;
}
let metrics = LineMetrics::new(document_text);
Some(Diagnostic {
range: metrics.range_for_vsg_lines(location.line, location.line),
severity: Some(DiagnosticSeverity::ERROR),
code: Some(NumberOrString::String("syntax".to_owned())),
source: Some(DIAGNOSTIC_SOURCE.to_owned()),
message: error.message.clone(),
..Diagnostic::default()
})
}
/// Legacy version-one documents predate the explicit completion marker.
const fn complete_by_default() -> bool {
true
@ -419,8 +471,8 @@ mod tests {
fn complete(output: &str, text: &str) -> Vec<tower_lsp::lsp_types::Diagnostic> {
match parse_diagnostics(output, text).expect("compatible protocol") {
DiagnosticResponse::Complete(diagnostics) => diagnostics,
DiagnosticResponse::Incomplete(reason) => {
panic!("unexpected incomplete response: {reason}")
DiagnosticResponse::Incomplete { message, .. } => {
panic!("unexpected incomplete response: {message}")
}
}
}
@ -429,7 +481,7 @@ mod tests {
fn incomplete(output: &str, text: &str) -> String {
match parse_diagnostics(output, text).expect("compatible protocol") {
DiagnosticResponse::Complete(_) => panic!("unexpected complete response"),
DiagnosticResponse::Incomplete(reason) => reason,
DiagnosticResponse::Incomplete { message, .. } => message,
}
}
@ -545,6 +597,46 @@ mod tests {
);
}
/// A located syntax failure becomes an editor diagnostic without correction data.
#[test]
fn converts_located_syntax_failure() {
let output = json!({
"schema": "vsg.diagnostics",
"schema_version": 1,
"complete": false,
"tool": {"name": "vsg", "version": "3.35.0"},
"source": {"name": "stdin"},
"rules": {},
"diagnostics": [],
"errors": [{
"kind": "syntax",
"message": "Unexpected token; expected ;",
"location": {"line": 2, "column": 3},
}],
})
.to_string();
let DiagnosticResponse::Incomplete {
message,
diagnostics,
} = parse_diagnostics(&output, "first\nabc\n").expect("compatible incomplete response")
else {
panic!("expected incomplete response")
};
assert!(message.contains("Unexpected token"));
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::ERROR));
assert_eq!(
diagnostics[0].range,
Range::new(Position::new(1, 0), Position::new(1, 3))
);
assert_eq!(
diagnostics[0].code,
Some(NumberOrString::String("syntax".to_owned()))
);
assert!(diagnostics[0].data.is_none());
}
/// Unknown protocol identities and versions fail visibly.
#[test]
fn rejects_unsupported_protocol() {

View File

@ -79,6 +79,8 @@ struct Document {
version: i32,
/// Most recent validated diagnostics for this version.
diagnostics: Vec<tower_lsp::lsp_types::Diagnostic>,
/// Whether VSG completed analysis for this exact document version.
analysis_complete: bool,
}
/// VSG-backed implementation of the Language Server Protocol.
@ -257,6 +259,9 @@ impl Backend {
if document.version != data.version {
return Err(Error::invalid_request());
}
if !document.analysis_complete {
return Err(Error::invalid_request());
}
let corrected = match data.correction {
Correction::All => {
@ -336,21 +341,47 @@ impl Backend {
return;
}
current.diagnostics.clone_from(&diagnostics);
current.analysis_complete = true;
drop(documents);
self.record_vsg_success().await;
self.client
.publish_diagnostics(uri, diagnostics, Some(document.version))
.await;
}
Ok(DiagnosticResponse::Incomplete(message)) => {
if self.is_current(&uri, document.version).await {
self.report_incomplete_diagnostics(message).await;
Ok(DiagnosticResponse::Incomplete {
message,
diagnostics,
}) => {
let mut documents = self.documents.write().await;
let Some(current) = documents.get_mut(&uri) else {
return;
};
if current.version != document.version {
return;
}
current.diagnostics.clone_from(&diagnostics);
current.analysis_complete = false;
drop(documents);
self.client
.publish_diagnostics(uri, diagnostics, Some(document.version))
.await;
self.report_incomplete_diagnostics(message).await;
}
Err(error) => {
if self.is_current(&uri, document.version).await {
self.report_vsg_error(&error).await;
let mut documents = self.documents.write().await;
let Some(current) = documents.get_mut(&uri) else {
return;
};
if current.version != document.version {
return;
}
current.diagnostics.clear();
current.analysis_complete = false;
drop(documents);
self.client
.publish_diagnostics(uri, Vec::new(), Some(document.version))
.await;
self.report_vsg_error(&error).await;
}
}
}
@ -535,7 +566,9 @@ impl LanguageServer for Backend {
};
let mut actions = Vec::new();
if action_kind_requested(&parameters, &CodeActionKind::QUICKFIX) {
if document.analysis_complete
&& action_kind_requested(&parameters, &CodeActionKind::QUICKFIX)
{
let mut selectors = std::collections::BTreeSet::new();
let mut documentation_urls = std::collections::BTreeSet::new();
let mut multi_rule_lines = std::collections::BTreeMap::<
@ -646,7 +679,7 @@ impl LanguageServer for Backend {
}
}
if action_kind_requested(&parameters, &FIX_ALL_KIND) {
if document.analysis_complete && action_kind_requested(&parameters, &FIX_ALL_KIND) {
actions.push(CodeActionOrCommand::CodeAction(CodeAction {
title: "Fix all VSG findings".to_owned(),
kind: Some(FIX_ALL_KIND),
@ -688,6 +721,9 @@ impl LanguageServer for Backend {
let Some(document) = self.snapshot(&uri).await else {
return Ok(None);
};
if !document.analysis_complete {
return Ok(None);
}
match self
.runner
@ -716,6 +752,7 @@ impl LanguageServer for Backend {
text: parameters.text_document.text,
version: parameters.text_document.version,
diagnostics: Vec::new(),
analysis_complete: false,
};
self.documents
.write()
@ -736,6 +773,7 @@ impl LanguageServer for Backend {
text: change.text,
version: parameters.text_document.version,
diagnostics: Vec::new(),
analysis_complete: false,
};
self.documents
.write()
@ -752,6 +790,7 @@ impl LanguageServer for Backend {
if let Some(text) = parameters.text {
document.text = text;
document.diagnostics.clear();
document.analysis_complete = false;
self.documents
.write()
.await
@ -793,6 +832,9 @@ mod tests {
/// Empty valid VSG diagnostic protocol document.
const EMPTY_DIAGNOSTICS: &str = r#"{"schema":"vsg.diagnostics","schema_version":1,"tool":{"name":"vsg","version":"3.35.0"},"source":{"name":"stdin"},"rules":{},"diagnostics":[]}"#;
/// Incomplete analysis containing a located parser failure.
const SYNTAX_FAILURE: &str = r#"{"schema":"vsg.diagnostics","schema_version":1,"complete":false,"tool":{"name":"vsg","version":"3.35.0"},"source":{"name":"stdin"},"rules":{},"diagnostics":[],"errors":[{"kind":"syntax","message":"Unexpected token; expected ;","location":{"line":2,"column":1}}]}"#;
/// Valid VSG result containing one warning.
const ONE_DIAGNOSTIC: &str = r#"{"schema":"vsg.diagnostics","schema_version":1,"tool":{"name":"vsg","version":"3.35.0"},"source":{"name":"stdin"},"rules":{"rule_001":{"severity":{"name":"Warning","type":"warning"},"fixable":true,"phase":1,"subphase":1,"configuration":{"disable":false},"documentation":{"rule":"https://example.com/rule-001","configuration":null}}},"diagnostics":[{"rule":"rule_001","location":{"start_line":1,"end_line":1},"message":"use lower case"}]}"#;
@ -2148,6 +2190,7 @@ mod tests {
text: "changed while fixing".to_owned(),
version: 2,
diagnostics: Vec::new(),
analysis_complete: false,
},
);
observed_runner.release.notify_one();
@ -2297,6 +2340,7 @@ mod tests {
text: "source".to_owned(),
version: 1,
diagnostics: Vec::new(),
analysis_complete: true,
},
);
@ -2341,6 +2385,9 @@ mod tests {
let cleared = published_diagnostics(&mut socket).await;
assert!(cleared.diagnostics.is_empty());
assert_eq!(cleared.version, None);
let failed = published_diagnostics(&mut socket).await;
assert!(failed.diagnostics.is_empty());
assert_eq!(failed.version, Some(1));
socket.next().await.expect("show-message notification")
};
let ((), request) = tokio::join!(open, receive);
@ -2378,6 +2425,9 @@ mod tests {
.await
.diagnostics
.is_empty());
let failed = published_diagnostics(&mut socket).await;
assert!(failed.diagnostics.is_empty());
assert_eq!(failed.version, Some(1));
socket.next().await.expect("warning notification")
};
let ((), warning) = tokio::join!(open, malformed);
@ -2401,6 +2451,69 @@ mod tests {
assert_eq!(recovered.diagnostics.len(), 1);
}
/// Parser failures replace stale style warnings and disable every correction action.
#[tokio::test]
async fn publishes_syntax_failure_and_suppresses_corrections() {
let runner = Arc::new(SequenceRunner {
results: Mutex::new(VecDeque::from([
Ok(ONE_DIAGNOSTIC.to_owned()),
Ok(SYNTAX_FAILURE.to_owned()),
])),
});
let (mut service, mut socket) =
LspService::new(move |client| Backend::new(client, runner.clone(), Vec::new()));
initialize(&mut service).await;
let initial = open_document(
&mut service,
&mut socket,
json!({"textDocument": {
"uri": "file:///tmp/example.vhd", "languageId": "vhdl",
"version": 1, "text": "entity demo is\nend entity;\n"
}}),
)
.await;
assert_eq!(initial.diagnostics.len(), 1);
let change = notify(
&mut service,
"textDocument/didChange",
json!({
"textDocument": {"uri": "file:///tmp/example.vhd", "version": 2},
"contentChanges": [{"text": "entity demo is\nbroken\n"}]
}),
);
let receive = async {
let diagnostics = published_diagnostics(&mut socket).await;
let warning = socket.next().await.expect("syntax warning notification");
(diagnostics, warning)
};
let ((), (published, warning)) = tokio::join!(change, receive);
assert_eq!(published.version, Some(2));
assert_eq!(published.diagnostics.len(), 1);
assert_eq!(
published.diagnostics[0].severity,
Some(tower_lsp::lsp_types::DiagnosticSeverity::ERROR)
);
assert_eq!(published.diagnostics[0].range.start.line, 1);
assert_eq!(
published.diagnostics[0].code,
Some(tower_lsp::lsp_types::NumberOrString::String(
"syntax".to_owned()
))
);
assert!(published.diagnostics[0].data.is_none());
assert_eq!(warning.method(), "window/showMessage");
let actions = request_code_actions(
&mut service,
serde_json::to_value(&published.diagnostics).expect("serialize syntax diagnostic"),
json!(["quickfix", "source.fixAll.vsg"]),
)
.await;
assert!(actions.is_null());
}
/// An explicit incompatible protocol version remains a loud error.
#[tokio::test]
async fn reports_incompatible_protocol_version_as_error() {
@ -2421,6 +2534,7 @@ mod tests {
);
let receive = async {
let _cleared = published_diagnostics(&mut socket).await;
let _failed = published_diagnostics(&mut socket).await;
socket.next().await.expect("error notification")
};
let ((), error) = tokio::join!(open, receive);
@ -2455,6 +2569,10 @@ mod tests {
}}),
);
let first_failure = async {
assert!(published_diagnostics(&mut socket)
.await
.diagnostics
.is_empty());
assert!(published_diagnostics(&mut socket)
.await
.diagnostics
@ -2473,6 +2591,10 @@ mod tests {
}),
)
.await;
assert!(published_diagnostics(&mut socket)
.await
.diagnostics
.is_empty());
assert!(timeout(Duration::from_millis(20), socket.next())
.await
.is_err());
@ -2497,7 +2619,13 @@ mod tests {
"contentChanges": [{"text": "broken again"}]
}),
);
let repeated_failure = socket.next();
let repeated_failure = async {
assert!(published_diagnostics(&mut socket)
.await
.diagnostics
.is_empty());
socket.next().await
};
let ((), repeated_failure) = tokio::join!(recurrence, repeated_failure);
assert_eq!(
repeated_failure
@ -2523,6 +2651,7 @@ mod tests {
text: "old".to_owned(),
version: 1,
diagnostics: Vec::new(),
analysis_complete: false,
};
service
.inner()
@ -2540,6 +2669,7 @@ mod tests {
text: "new".to_owned(),
version: 2,
diagnostics: Vec::new(),
analysis_complete: false,
},
);
observed_runner.release.notify_one();

View File

@ -48,6 +48,9 @@ async fn packaged_vsg_supports_bridge_protocol() {
assert!(incomplete["errors"]
.as_array()
.is_some_and(|errors| !errors.is_empty()));
assert_eq!(incomplete["errors"][0]["kind"], "syntax");
assert_eq!(incomplete["errors"][0]["location"]["line"], 1);
assert_eq!(incomplete["errors"][0]["location"]["column"], 1);
let invalid_source = "entity incomplete is\n";
let unchanged = runner