diff --git a/README.md b/README.md index 419a2fd..bd115b4 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,12 @@ to request that action. For deliberately unformatted files and expected interactions, see the [LSP showcase](showcase/README.md). +An additional multi-rule action is available behind +`--experimental-multi-rule-line-fix`. It is disabled by default because VSG +phases can move later findings to different lines. See the +[experimental action safety notes](doc/experimental-multi-rule-line-fix.md) +before enabling it. + ## More documentation - [Installation alternatives and PATH troubleshooting](doc/installation.md) diff --git a/doc/editor-configuration.md b/doc/editor-configuration.md index 0ec79cf..8968828 100644 --- a/doc/editor-configuration.md +++ b/doc/editor-configuration.md @@ -32,6 +32,11 @@ To use VSG configuration files, add arguments to the server entry. Repeat args = ["-c", "vhdl/config.yaml"] ``` +The experimental grouped same-line action additionally requires +`--experimental-multi-rule-line-fix` in this argument list. It is deliberately +off by default; read its [safety notes](experimental-multi-rule-line-fix.md) +before enabling it. + If another VHDL server is installed, it can run alongside the bridge: ```toml diff --git a/doc/experimental-multi-rule-line-fix.md b/doc/experimental-multi-rule-line-fix.md new file mode 100644 index 0000000..c072e53 --- /dev/null +++ b/doc/experimental-multi-rule-line-fix.md @@ -0,0 +1,34 @@ +# Experimental multi-rule line correction + +Start the bridge with `--experimental-multi-rule-line-fix` to add one action +for all distinct fixable VSG rules reported on a diagnosed line. The normal +single-rule Quick Fixes remain available. The bridge submits every selector to +one VSG process so VSG retains control of phase ordering; it never loops over +stale line numbers. + +This action is intentionally disabled by default. Rules from an early phase can +insert or delete lines before later rules inspect their selector. In the +`one-line-entity.vhd` showcase, the phase-one newline correction makes progress +but exposes an `entity_009` indentation finding, while the original phase-six +end-name selector moves to line 2. A second request using the old line-1 +selectors is a no-op. This named regression is asserted by the packaged-VSG +integration test rather than silently treated as a complete correction. + +The normal suite includes a fixed-seed (`0x5eed`) 128-case structured edit +property test covering indentation, whitespace, line insertion, casing, +Unicode, LF, and CRLF. It also verifies selector deduplication, one-process +batching, no-op behavior, stale-version rejection, cancellation, and exact LSP +edit reproduction. The opt-in packaged-VSG test diagnoses the corrected output +again and checks monotonic progress for the showcase case: + +```sh +VSG_EXECUTABLE=/path/to/venv/bin/vsg \ + cargo test --test packaged_vsg -- --ignored +``` + +The gate must remain until every fixable rule family and phase has a curated +case, known line-shift regressions are resolved or explicitly accepted, a +longer fuzz campaign has no unexplained regression, the packaged release pair +passes, and the behavior has been manually verified in Helix. Current tests are +useful safety coverage, not promotion evidence for enabling the action by +default. diff --git a/showcase/README.md b/showcase/README.md index 9d61169..118e260 100644 --- a/showcase/README.md +++ b/showcase/README.md @@ -22,6 +22,10 @@ on one line and rules from different VSG phases. You should be able to: 3. select an individual Quick Fix for one rule on line 1; 4. select `Fix all VSG findings` to run the normal phase-seven formatter. +To inspect the opt-in grouped action, add +`--experimental-multi-rule-line-fix` to the bridge arguments. The action is +clearly labelled Experimental and does not replace the individual fixes. + Then open `demo_design.vhd` to inspect findings and fixes across an entity, port clause, architecture, operators, indentation, and identifier casing. The configuration deliberately changes `entity_008` to Warning so both LSP Error diff --git a/src/edits.rs b/src/edits.rs index 3bdb21a..062e38b 100644 --- a/src/edits.rs +++ b/src/edits.rs @@ -97,6 +97,43 @@ mod tests { edit.clone() } + /// Converts a UTF-16 LSP position to a byte boundary in test text. + fn byte_offset(text: &str, position: Position) -> usize { + let mut offset = 0; + for (index, line) in text.split_inclusive('\n').enumerate() { + if index == position.line as usize { + let content = line.strip_suffix('\n').unwrap_or(line); + let content = content.strip_suffix('\r').unwrap_or(content); + let mut utf16 = 0; + for (byte, character) in content.char_indices() { + if utf16 == position.character { + return offset + byte; + } + utf16 += u32::try_from(character.len_utf16()).expect("UTF-16 width"); + } + assert_eq!(utf16, position.character); + return offset + content.len(); + } + offset += line.len(); + } + assert_eq!( + position.line as usize, + text.bytes().filter(|byte| *byte == b'\n').count() + ); + assert_eq!(position.character, 0); + text.len() + } + + /// Applies one computed LSP edit and checks the complete resulting text. + fn assert_reproduces(original: &str, corrected: &str) { + let edit = edit(original, corrected); + let start = byte_offset(original, edit.range.start); + let end = byte_offset(original, edit.range.end); + let mut applied = original.to_owned(); + applied.replace_range(start..end, &edit.new_text); + assert_eq!(applied, corrected); + } + /// A same-line change produces a whole-line replacement. #[test] fn replaces_one_complete_line() { @@ -142,4 +179,44 @@ mod tests { ) .is_none()); } + + /// A deterministic corpus covers boundaries, line shifts, Unicode, and CRLF. + #[test] + fn line_edits_reproduce_structured_corpus() { + for (original, corrected) in [ + ("bad", "GOOD"), + ("first\nbad\nlast\n", "first\nGOOD\nlast\n"), + ("first\nlast", "first\ninserted\nlast"), + ("first\nremoved\nlast", "first\nlast"), + ("é😀\nlast", "É😀\nlast"), + ("first\r\nbad\r\nlast\r\n", "first\r\nGOOD\r\nlast\r\n"), + ("first\nlast", "inserted\nfirst\nlast"), + ("first\nlast", "first\nlast\ninserted\n"), + ] { + assert_reproduces(original, corrected); + } + } + + /// Fixed-seed structured mutations exercise many whole-line edit shapes. + #[test] + fn line_edits_reproduce_bounded_generated_cases() { + let mut state = 0x5eed_u64; + for case in 0..128 { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1); + let indent = " ".repeat((state as usize) % 9); + let ending = if state & 1 == 0 { "\n" } else { "\r\n" }; + let original = format!("entity sample is{ending}{indent}é😀 <= a;{ending}end;{ending}"); + let corrected = match case % 4 { + 0 => format!("entity SAMPLE is{ending}{indent}é😀 <= a;{ending}end;{ending}"), + 1 => { + format!("entity sample is{ending}{indent}é😀 <= a;{ending}{ending}end;{ending}") + } + 2 => format!("entity sample is{ending}{indent}é😀<=a;{ending}end;{ending}"), + _ => format!("entity sample is{ending} {indent}é😀 <= a;{ending}end;{ending}"), + }; + assert_reproduces(&original, &corrected); + } + } } diff --git a/src/lib.rs b/src/lib.rs index 41f001d..733bfe1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,6 +26,9 @@ pub struct Options { /// VSG configuration files, in the order in which VSG should load them. #[arg(short, long)] pub configuration: Vec, + /// Offers an opt-in action that fixes all reported rules on one line. + #[arg(long)] + pub experimental_multi_rule_line_fix: bool, } impl Options { @@ -58,6 +61,7 @@ where let vsg_arguments = options.vsg_arguments(); let (service, socket) = LspService::new(move |client| { Backend::new(client, Arc::clone(&runner), vsg_arguments.clone()) + .with_experimental_multi_rule_line_fix(options.experimental_multi_rule_line_fix) }); Server::new(input, output, socket).serve(service).await; @@ -138,6 +142,17 @@ mod tests { .expect("options without configuration files are valid"); assert!(options.vsg_arguments().is_empty()); + assert!(!options.experimental_multi_rule_line_fix); + } + + /// The multi-rule line action requires an explicit runtime opt-in. + #[test] + fn parses_experimental_multi_rule_line_flag() { + let options = + Options::try_parse_from(["vsg_bridge_ls", "--experimental-multi-rule-line-fix"]) + .expect("experimental flag is valid"); + + assert!(options.experimental_multi_rule_line_fix); } /// The byte-stream transport processes a complete LSP lifecycle. @@ -150,6 +165,7 @@ mod tests { response_writer, Options { configuration: Vec::new(), + experimental_multi_rule_line_fix: false, }, Arc::new(UnusedRunner), )); diff --git a/src/server.rs b/src/server.rs index b5642aa..0f6d0ff 100644 --- a/src/server.rs +++ b/src/server.rs @@ -50,6 +50,8 @@ pub struct Backend { documents: RwLock>, /// Whether the initialized client accepts `window/showDocument` requests. show_document_supported: AtomicBool, + /// Enables the opt-in multi-rule action without changing stable actions. + experimental_multi_rule_line_fix: bool, } impl Backend { @@ -62,9 +64,17 @@ impl Backend { vsg_arguments, documents: RwLock::new(HashMap::new()), show_document_supported: AtomicBool::new(false), + experimental_multi_rule_line_fix: false, } } + /// Enables or disables the experimental multi-rule line action. + #[must_use] + pub fn with_experimental_multi_rule_line_fix(mut self, enabled: bool) -> Self { + self.experimental_multi_rule_line_fix = enabled; + self + } + /// Runs VSG and publishes results only if the snapshot is still current. async fn lint_and_publish(&self, uri: Url, document: Document) { let result = self @@ -234,6 +244,10 @@ impl LanguageServer for Backend { if action_kind_requested(¶meters, &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::< + u32, + (std::collections::BTreeSet, Vec<_>), + >::new(); for requested in ¶meters.context.diagnostics { let Some(current) = document .diagnostics @@ -252,6 +266,13 @@ impl LanguageServer for Backend { continue; } + if data.metadata.fixable { + let (rules, diagnostics) = multi_rule_lines.entry(data.line).or_default(); + if rules.insert(data.rule.clone()) { + diagnostics.push(current.clone()); + } + } + if data.metadata.fixable && selectors.insert((data.rule.clone(), data.line)) { match self .runner @@ -311,6 +332,48 @@ impl LanguageServer for Backend { } } } + + if self.experimental_multi_rule_line_fix { + for (line, (rules, diagnostics)) in multi_rule_lines { + if rules.len() < 2 { + continue; + } + let selectors: Vec<_> = rules.into_iter().map(|rule| (rule, line)).collect(); + match self + .runner + .fix_rules(&document.text, &self.vsg_arguments, &selectors) + .await + { + Ok(corrected) => { + if !self.is_current(&uri, document.version).await { + return Err(Error::invalid_request()); + } + if let Some(edit) = workspace_edit( + uri.clone(), + document.version, + &document.text, + &corrected, + ) { + actions.push(CodeActionOrCommand::CodeAction(CodeAction { + title: format!( + "Experimental: fix {} VSG rules on line {line}", + selectors.len() + ), + kind: Some(CodeActionKind::QUICKFIX), + diagnostics: Some(diagnostics), + edit: Some(edit), + ..CodeAction::default() + })); + } + } + Err(error) => { + self.client + .show_message(MessageType::ERROR, error.to_string()) + .await; + } + } + } + } } if action_kind_requested(¶meters, &FIX_ALL_KIND) { @@ -1019,6 +1082,61 @@ mod tests { ); } + /// The opt-in path sends all same-line rules through one additional process. + #[tokio::test] + async fn offers_experimental_multi_rule_line_fix_when_enabled() { + let mut runner = ActionRunner::successful("ENTITY demo IS", "unused"); + runner.lint = action_document( + json!({"rule_001": action_rule(true), "rule_002": action_rule(true)}), + json!([ + {"rule": "rule_001", "location": {"start_line": 1, "end_line": 1}, "message": "first"}, + {"rule": "rule_002", "location": {"start_line": 1, "end_line": 1}, "message": "second"} + ]), + ); + let runner = Arc::new(runner); + let observed_runner = Arc::clone(&runner); + let (mut service, mut socket) = LspService::new(move |client| { + Backend::new(client, runner.clone(), Vec::new()) + .with_experimental_multi_rule_line_fix(true) + }); + initialize(&mut service).await; + notify( + &mut service, + "textDocument/didOpen", + json!({"textDocument": { + "uri": "file:///tmp/example.vhd", "languageId": "vhdl", + "version": 1, "text": "entity demo is" + }}), + ) + .await; + let published = published_diagnostics(&mut socket).await; + + let result = request_code_actions( + &mut service, + serde_json::to_value(&published.diagnostics).expect("serialize diagnostics"), + json!(["quickfix"]), + ) + .await; + + assert_eq!(result.as_array().expect("action list").len(), 3); + assert!(result + .as_array() + .expect("action list") + .iter() + .any(|action| action["title"] == "Experimental: fix 2 VSG rules on line 1")); + assert_eq!( + observed_runner + .selectors + .lock() + .expect("selector lock") + .last(), + Some(&vec![ + ("rule_001".to_owned(), 1), + ("rule_002".to_owned(), 1) + ]) + ); + } + /// Non-fixable rule metadata never produces a correction action. #[tokio::test] async fn omits_non_fixable_rule_actions() { diff --git a/tests/fixtures/invalid-utf8-vsg.sh b/tests/fixtures/invalid-utf8-vsg.sh index 971483a..06da764 100755 --- a/tests/fixtures/invalid-utf8-vsg.sh +++ b/tests/fixtures/invalid-utf8-vsg.sh @@ -1,4 +1,5 @@ #!/bin/sh set -eu +cat >/dev/null printf '\377' diff --git a/tests/packaged_vsg.rs b/tests/packaged_vsg.rs index 662b853..e24e5d9 100644 --- a/tests/packaged_vsg.rs +++ b/tests/packaged_vsg.rs @@ -47,4 +47,47 @@ async fn packaged_vsg_supports_bridge_protocol() { .expect("packaged VSG fix-all"); assert_ne!(fixed, source); assert!(fixed.lines().count() > source.lines().count()); + + let multi_selectors = vec![ + ("entity_008".to_owned(), 1), + ("entity_012".to_owned(), 1), + ("entity_021".to_owned(), 1), + ("entity_026".to_owned(), 1), + ]; + let multi = runner + .fix_rules(&source, &arguments, &multi_selectors) + .await + .expect("packaged VSG multi-rule line fix"); + let diagnosed_multi: Value = serde_json::from_str( + &runner + .lint(&multi, &arguments) + .await + .expect("diagnose multi-rule result"), + ) + .expect("valid diagnostics after multi-rule fix"); + assert_eq!(diagnosed_multi["schema_version"], 1); + let after = diagnosed_multi["diagnostics"] + .as_array() + .expect("diagnostic array after multi-rule fix"); + let selected_remaining = after + .iter() + .filter(|diagnostic| { + diagnostic["rule"] + .as_str() + .is_some_and(|rule| multi_selectors.iter().any(|(selected, _)| selected == rule)) + }) + .count(); + assert!(selected_remaining < multi_selectors.len()); + assert!( + after + .iter() + .any(|diagnostic| diagnostic["rule"] == "entity_009"), + "the known phase-one newline currently exposes an indentation finding" + ); + + let repeated = runner + .fix_rules(&multi, &arguments, &multi_selectors) + .await + .expect("repeat packaged VSG multi-rule line fix"); + assert_eq!(repeated, multi, "second identical request must be a no-op"); }