Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat: adds suggestions to `QuoteSpacing` (#3724)
Andrew Dunbar2a0d61668d90
diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rsindex 66f526eed..31449d708 100644--- a/harper-core/src/linting/mod.rs+++ b/harper-core/src/linting/mod.rs@@ -676,7 +676,14 @@ pub mod tests {/// See issue #950: https://github.com/Automattic/harper/issues/950#[track_caller]pub fn assert_suggestion_result(text: &str, mut linter: impl Linter, needle: &str) {- if search_for_suggestion(DocumentType::PlainEnglish, text, &mut linter, needle, 0) {+ if search_for_suggestion(+ DocumentType::PlainEnglish,+ text,+ &mut linter,+ needle,+ 0,+ SearchStrategy::AllSuggestions,+ ) {return;}@@ -686,14 +693,50 @@ pub mod tests {);}+ /// Use this when you want to verify that the first suggestion is the most likely correct fix.+ /// Handy for linters which offer multiple suggestions but prioritize their best guess.+ #[track_caller]+ pub fn assert_first_suggestion_result(text: &str, mut linter: impl Linter, needle: &str) {+ if search_for_suggestion(+ DocumentType::PlainEnglish,+ text,+ &mut linter,+ needle,+ 0,+ SearchStrategy::FirstSuggestionOnly,+ ) {+ return;+ }++ panic!(+ "The primary suggestion sequence failed to produce the expected result.\n\+ Expected: \"{needle}\""+ );+ }+/// DFS implementation using markdown instead of plain English#[track_caller]pub fn assert_markdown_suggestion_result(text: &str, mut linter: impl Linter, needle: &str) {- if !search_for_suggestion(DocumentType::Markdown, text, &mut linter, needle, 0) {+ if !search_for_suggestion(+ DocumentType::Markdown,+ text,+ &mut linter,+ needle,+ 0,+ SearchStrategy::AllSuggestions,+ ) {panic!("No suggestion sequence produced the expected result.\nExpected: {needle}");}}+ #[derive(Copy, Clone, PartialEq, Eq)]+ enum SearchStrategy {+ /// Explores all suggestion sequences (the current default behavioral standard).+ AllSuggestions,+ /// Only explores the very first suggestion path (for validating primary/best fixes).+ FirstSuggestionOnly,+ }+/// Recursively searches all suggestion combinations using depth-first search./// Returns true if any path reaches the expected result, false otherwise.fn search_for_suggestion(@@ -702,6 +745,7 @@ pub mod tests {linter: &mut impl Linter,needle: &str,depth: usize,+ strategy: SearchStrategy,) -> bool {// Prevent infinite recursion (e.g. cycles in suggestions)if depth > super::MAX_SUGGESTION_TRANSFORMATION_DEPTH {@@ -730,9 +774,14 @@ pub mod tests {let next: String = chars_copy.iter().collect();// Recursively search this branch- if search_for_suggestion(doc_type, &next, linter, needle, depth + 1) {+ if search_for_suggestion(doc_type, &next, linter, needle, depth + 1, strategy) {return true;}++ // If we're only checking the first suggestion, stop after the first one+ if strategy == SearchStrategy::FirstSuggestionOnly {+ break;+ }}}@@ -795,6 +844,7 @@ pub mod tests {&mut linter,bad_suggestion,0,+ SearchStrategy::AllSuggestions,) {return;}diff --git a/harper-core/src/linting/quote_spacing.rs b/harper-core/src/linting/quote_spacing.rsindex 60529da8e..0778241bd 100644--- a/harper-core/src/linting/quote_spacing.rs+++ b/harper-core/src/linting/quote_spacing.rs@@ -1,8 +1,8 @@-use crate::expr::{ExprExt, SequenceExpr};-use crate::linting::LintKind;-use crate::{Document, TokenStringExt};--use super::{Lint, Linter};+use crate::{+ expr::{ExprExt, SequenceExpr},+ linting::{Lint, LintKind, Linter},+ {Document, Punctuation, TokenKind, TokenStringExt},+};pub struct QuoteSpacing {expr: SequenceExpr,@@ -29,14 +29,35 @@ impl Linter for QuoteSpacing {for m in self.expr.iter_matches_in_doc(document) {let matched_tokens = m.get_content(document.get_tokens());- let Some(span) = matched_tokens.span() else {+ let Some(_span) = matched_tokens.span() else {continue;};+ let quote_tok = &matched_tokens[1];++ // Is this an opening or closing quote?+ let quote_index = m.start + 1; // Quote is the second token in the match+ let is_closing = if let TokenKind::Punctuation(Punctuation::Quote(q)) = quote_tok.kind {+ // If twin_loc points backward, this is a closing quote+ q.twin_loc.is_some_and(|twin| twin < quote_index)+ } else {+ false+ };++ let mut suggestions = vec![+ super::Suggestion::ReplaceWith(vec![' ', '"']),+ super::Suggestion::ReplaceWith(vec!['"', ' ']),+ ];++ // For closing quotes, space likely should be after it+ if is_closing {+ suggestions.swap(0, 1);+ }+lints.push(Lint {- span,+ span: matched_tokens[1].span,lint_kind: LintKind::Formatting,- suggestions: vec![],+ suggestions,message: "A quote must be preceded or succeeded by a space.".to_owned(),priority: 31,})@@ -53,7 +74,10 @@ impl Linter for QuoteSpacing {#[cfg(test)]mod tests {use super::QuoteSpacing;- use crate::linting::tests::{assert_lint_count, assert_no_lints};+ use crate::linting::tests::{+ assert_first_suggestion_result, assert_lint_count, assert_no_lints,+ assert_suggestion_result,+ };#[test]fn flags_missing_space_before_quote() {@@ -78,4 +102,46 @@ mod tests {fn allows_quotes_at_end_of_sentence() {assert_no_lints("They shouted \"charge.\"", QuoteSpacing::default());}++ #[test]+ fn fix_by_inserting_space_after() {+ assert_suggestion_result(+ "It's not a complete sentence since it lacks a verb but it would be valid as a title or answer to a question since \"dog runs\"are things which exist",+ QuoteSpacing::default(),+ "It's not a complete sentence since it lacks a verb but it would be valid as a title or answer to a question since \"dog runs\" are things which exist",+ );+ }++ #[test]+ fn ensure_first_suggestion_is_space_then_quote() {+ assert_first_suggestion_result(+ "foo\"bar\" bar",+ QuoteSpacing::default(),+ "foo \"bar\" bar",+ );+ }++ #[test]+ fn ensure_first_suggestion_is_quote_then_space() {+ assert_first_suggestion_result(+ "foo \"bar\"bar",+ QuoteSpacing::default(),+ "foo \"bar\" bar",+ );+ }++ #[test]+ #[should_panic]+ fn ensure_first_suggestion_is_not_quote_then_space() {+ assert_first_suggestion_result(+ "foo \"bar\"bar",+ QuoteSpacing::default(),+ "foo\" bar\" bar",+ );+ }++ #[test]+ fn ensure_quote_then_space_is_suggested_even_when_wrong() {+ assert_suggestion_result("foo\"bar\" bar", QuoteSpacing::default(), "foo\" bar\" bar");+ }}