Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat: If I would've done→If I had done (#2214)

Andrew Dunbarb5893dda887c
diff --git a/harper-core/src/char_string.rs b/harper-core/src/char_string.rs
index 72978461b..43007a65b 100644
--- a/harper-core/src/char_string.rs
+++ b/harper-core/src/char_string.rs
@@ -30,6 +30,14 @@ pub trait CharStringExt {
/// Only normalizes the left side to lowercase and avoids allocations.
fn eq_any_ignore_ascii_case_chars(&self, others: &[&[char]]) -> bool;
+ /// Case-insensitive check if the string starts with the given ASCII prefix.
+ /// The prefix is assumed to be lowercase.
+ fn starts_with_ignore_ascii_case_str(&self, prefix: &str) -> bool;
+
+ /// Case-insensitive check if the string starts with any of the given ASCII prefixes.
+ /// The prefixes are assumed to be lowercase.
+ fn starts_with_any_ignore_ascii_case_str(&self, prefixes: &[&str]) -> bool;
+
/// Case-insensitive check if the string ends with the given ASCII suffix.
/// The suffix is assumed to be lowercase.
fn ends_with_ignore_ascii_case_chars(&self, suffix: &[char]) -> bool;
@@ -97,6 +105,23 @@ impl CharStringExt for [char] {
.any(|chars| self.eq_ignore_ascii_case_chars(chars))
}
+ fn starts_with_ignore_ascii_case_str(&self, prefix: &str) -> bool {
+ let prefix_len = prefix.len();
+ if self.len() < prefix_len {
+ return false;
+ }
+ self.iter()
+ .take(prefix_len)
+ .zip(prefix.chars())
+ .all(|(a, b)| a.to_ascii_lowercase() == b)
+ }
+
+ fn starts_with_any_ignore_ascii_case_str(&self, prefixes: &[&str]) -> bool {
+ prefixes
+ .iter()
+ .any(|prefix| self.starts_with_ignore_ascii_case_str(prefix))
+ }
+
fn ends_with_ignore_ascii_case_str(&self, suffix: &str) -> bool {
let suffix_len = suffix.len();
if self.len() < suffix_len {
diff --git a/harper-core/src/linting/if_wouldve.rs b/harper-core/src/linting/if_wouldve.rs
new file mode 100644
index 000000000..7e22e0d6b
--- /dev/null
+++ b/harper-core/src/linting/if_wouldve.rs
@@ -0,0 +1,198 @@
+use crate::expr::{Expr, SequenceExpr};
+use crate::linting::{ExprLinter, LintKind, Suggestion};
+use crate::patterns::{NominalPhrase, WordSet};
+use crate::token_string_ext::TokenStringExt;
+use crate::{CharStringExt, Lint, Token};
+
+pub struct IfWouldve {
+ expr: Box<dyn Expr>,
+}
+
+impl Default for IfWouldve {
+ fn default() -> Self {
+ Self {
+ expr: Box::new(
+ SequenceExpr::aco("if")
+ .t_ws()
+ .then(NominalPhrase)
+ .t_ws()
+ .then_any_of(vec![
+ Box::new(
+ SequenceExpr::default()
+ .then_word_set(&["would", "had"])
+ .t_ws()
+ .then_word_set(&["have", "of"]),
+ ),
+ Box::new(WordSet::new(&["would've", "wouldve", "had've", "hadve"])),
+ ])
+ .t_ws()
+ .then_verb_past_participle_form(),
+ ),
+ }
+ }
+}
+
+impl ExprLinter for IfWouldve {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
+ }
+
+ /// Identifies and corrects incorrect conditional phrases like "would've", "would have", "would of", etc.
+ /// to use the correct "had" construction in conditional statements.
+ fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
+ // We examine tokens in pairs, moving backwards from the end of the phrase
+ // to find the incorrect verb construction to replace with "had".
+ // The pattern we're looking for is: [if] [NP] [would/had] [have/of/ve] [verb]
+
+ // Start from the end of the token sequence (before the verb)
+ let matched_tokens = (2..toks.len() - 2)
+ .rev()
+ .step_by(2) // Check every other token since we're looking at pairs
+ .find_map(|i| {
+ let prev = toks[i - 2].span.get_content(src);
+ let curr = toks[i].span.get_content(src);
+
+ let would_had = &["would", "had"];
+
+ // Determine which tokens to replace based on the pattern
+ match () {
+ // Handle contractions like "would've" or "had've"
+ _ if curr.ends_with_ignore_ascii_case_str("ve") => {
+ if curr.starts_with_any_ignore_ascii_case_str(would_had) {
+ Some(&toks[i..=i]) // Single token like "would've"
+ } else if prev.starts_with_any_ignore_ascii_case_str(would_had) {
+ Some(&toks[i - 2..=i]) // Two tokens like "would have"
+ } else {
+ None
+ }
+ }
+ // Handle "would of" / "had of"
+ _ if curr.ends_with_ignore_ascii_case_str("of")
+ && prev.starts_with_any_ignore_ascii_case_str(would_had) =>
+ {
+ Some(&toks[i - 2..=i])
+ }
+ _ => None,
+ }
+ });
+
+ matched_tokens.and_then(|tokens_to_replace| {
+ let span = tokens_to_replace.span()?;
+
+ Some(Lint {
+ span,
+ lint_kind: LintKind::Nonstandard,
+ suggestions: vec![Suggestion::replace_with_match_case(
+ vec!['h', 'a', 'd'],
+ span.get_content(src),
+ )],
+ message: "If this is counterfactual or hypothetical, use `had` after `if` rather than `would have` or `had have`.".to_string(),
+ ..Default::default()
+ })
+ })
+ }
+
+ fn description(&self) -> &str {
+ "Corrects `if I would've done` etc. to `if I had done` etc."
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::linting::tests::{assert_no_lints, assert_suggestion_result};
+
+ use super::*;
+
+ #[test]
+ fn flag_if_i_wouldve_done_x() {
+ assert_suggestion_result(
+ "If I would've done X...",
+ IfWouldve::default(),
+ "If I had done X...",
+ );
+ }
+
+ #[test]
+ fn flag_if_you_would_have_done_y() {
+ assert_suggestion_result(
+ "If you would have done Y...",
+ IfWouldve::default(),
+ "If you had done Y...",
+ );
+ }
+
+ #[test]
+ fn flag_if_we_would_of_z() {
+ assert_suggestion_result(
+ "If we would of done Z...",
+ IfWouldve::default(),
+ "If we had done Z...",
+ );
+ }
+
+ #[test]
+ fn flag_if_he_hadve_done_w() {
+ assert_suggestion_result(
+ "If he hadve done W...",
+ IfWouldve::default(),
+ "If he had done W...",
+ );
+ }
+
+ #[test]
+ fn flag_if_she_hadve_done_x() {
+ assert_suggestion_result(
+ "If she had've done X...",
+ IfWouldve::default(),
+ "If she had done X...",
+ );
+ }
+
+ #[test]
+ fn flag_if_it_had_of_done_x() {
+ assert_suggestion_result(
+ "If it had of done X...",
+ IfWouldve::default(),
+ "If it had done X...",
+ );
+ }
+
+ #[test]
+ fn flag_if_np_wouldve() {
+ assert_suggestion_result(
+ "If that guy would've thought it through...",
+ IfWouldve::default(),
+ "If that guy had thought it through...",
+ );
+ }
+
+ // The linter cannot yet detect when this pattern is a counterfactual.
+ // If you can improve this linter to do so, here are some example sentences.
+
+ #[test]
+ #[ignore = "Can't detect correct use not in counterfactual"]
+ fn dont_flag_non_counterfactual_done() {
+ assert_no_lints(
+ "I don't know if they would have done that for a designer",
+ IfWouldve::default(),
+ );
+ }
+
+ #[test]
+ #[ignore = "Can't detect correct use not in counterfactual"]
+ fn dont_flag_non_counterfactual_gotten() {
+ assert_no_lints(
+ "I don't know if a normal programmer would have gotten that treatment.",
+ IfWouldve::default(),
+ );
+ }
+
+ #[test]
+ #[ignore = "Can't detect correct use not in counterfactual"]
+ fn dont_flag_non_counterfactual_been() {
+ assert_no_lints(
+ "I don't know if they would have been interested anyway",
+ IfWouldve::default(),
+ );
+ }
+}
diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rs
index fd668d677..4a06f7f4a 100644
--- a/harper-core/src/linting/lint_group.rs
+++ b/harper-core/src/linting/lint_group.rs
@@ -72,6 +72,7 @@ use super::hop_hope::HopHope;
use super::how_to::HowTo;
use super::hyphenate_number_day::HyphenateNumberDay;
use super::i_am_agreement::IAmAgreement;
+use super::if_wouldve::IfWouldve;
use super::in_on_the_cards::InOnTheCards;
use super::inflected_verb_after_to::InflectedVerbAfterTo;
use super::interested_in::InterestedIn;
@@ -515,6 +516,7 @@ impl LintGroup {
insert_struct_rule!(HowTo, true);
insert_expr_rule!(HyphenateNumberDay, true);
insert_expr_rule!(IAmAgreement, true);
+ insert_expr_rule!(IfWouldve, true);
insert_expr_rule!(InterestedIn, true);
insert_expr_rule!(ItLooksLikeThat, true);
insert_struct_rule!(ItsContraction, true);
diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rs
index 5b6aa34b8..a29e538da 100644
--- a/harper-core/src/linting/mod.rs
+++ b/harper-core/src/linting/mod.rs
@@ -69,6 +69,7 @@ mod hope_youre;
mod how_to;
mod hyphenate_number_day;
mod i_am_agreement;
+mod if_wouldve;
mod in_on_the_cards;
mod inflected_verb_after_to;
mod initialism_linter;
@@ -250,6 +251,7 @@ pub use hop_hope::HopHope;
pub use how_to::HowTo;
pub use hyphenate_number_day::HyphenateNumberDay;
pub use i_am_agreement::IAmAgreement;
+pub use if_wouldve::IfWouldve;
pub use in_on_the_cards::InOnTheCards;
pub use inflected_verb_after_to::InflectedVerbAfterTo;
pub use initialism_linter::InitialismLinter;