Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(core): Add various new rules (#2084)
Elijah Potter27188504b1b9
diff --git a/harper-core/src/linting/didnt.rs b/harper-core/src/linting/didnt.rsnew file mode 100644index 000000000..1a0f459c7--- /dev/null+++ b/harper-core/src/linting/didnt.rs@@ -0,0 +1,129 @@+use crate::Token;+use crate::expr::{Expr, SequenceExpr};+use crate::linting::{ExprLinter, Lint, LintKind, Suggestion};++pub struct Didnt {+ expr: Box<dyn Expr>,+}++impl Default for Didnt {+ fn default() -> Self {+ let pattern = SequenceExpr::default()+ .then_personal_pronoun()+ .t_ws()+ .t_aco("dint");++ Self {+ expr: Box::new(pattern),+ }+ }+}++impl ExprLinter for Didnt {+ fn expr(&self) -> &dyn Expr {+ self.expr.as_ref()+ }++ fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {+ let suspect = toks.last()?;++ Some(Lint {+ span: suspect.span,+ lint_kind: LintKind::Typo,+ suggestions: vec![Suggestion::replace_with_match_case_str(+ "didn't",+ suspect.span.get_content(src),+ )],+ message: "Consider using `didn't` here.".to_string(),+ priority: 63,+ })+ }++ fn description(&self) -> &str {+ "Corrects `dint` to `didn't` after subject pronouns."+ }+}++#[cfg(test)]+mod tests {+ use super::Didnt;+ use crate::linting::tests::{assert_lint_count, assert_no_lints, assert_suggestion_result};++ #[test]+ fn corrects_i_dint() {+ assert_suggestion_result(+ "I dint lock the gate.",+ Didnt::default(),+ "I didn't lock the gate.",+ );+ }++ #[test]+ fn corrects_you_dint() {+ assert_suggestion_result(+ "You dint look this way.",+ Didnt::default(),+ "You didn't look this way.",+ );+ }++ #[test]+ fn corrects_he_dint() {+ assert_suggestion_result(+ "He dint see the sign.",+ Didnt::default(),+ "He didn't see the sign.",+ );+ }++ #[test]+ fn corrects_she_dint() {+ assert_suggestion_result(+ "She dint call me back.",+ Didnt::default(),+ "She didn't call me back.",+ );+ }++ #[test]+ fn corrects_we_dint() {+ assert_suggestion_result(+ "We dint sleep much.",+ Didnt::default(),+ "We didn't sleep much.",+ );+ }++ #[test]+ fn corrects_they_dint() {+ assert_suggestion_result(+ "They dint enjoy the show.",+ Didnt::default(),+ "They didn't enjoy the show.",+ );+ }++ #[test]+ fn corrects_it_dint() {+ assert_suggestion_result(+ "It dint rain today.",+ Didnt::default(),+ "It didn't rain today.",+ );+ }++ #[test]+ fn does_not_flag_dint_noun() {+ assert_no_lints("The blow left a small dint in the metal.", Didnt::default());+ }++ #[test]+ fn does_not_flag_quoted_dint() {+ assert_no_lints("He muttered 'dint' under his breath.", Didnt::default());+ }++ #[test]+ fn does_not_flag_past_tense_with_not() {+ assert_lint_count("I did not lock the gate.", Didnt::default(), 0);+ }+}diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rsindex d60992305..95c19679b 100644--- a/harper-core/src/linting/lint_group.rs+++ b/harper-core/src/linting/lint_group.rs@@ -35,6 +35,7 @@ use super::confident::Confident;use super::correct_number_suffix::CorrectNumberSuffix;use super::criteria_phenomena::CriteriaPhenomena;use super::despite_of::DespiteOf;+use super::didnt::Didnt;use super::discourse_markers::DiscourseMarkers;use super::dot_initialisms::DotInitialisms;use super::double_modal::DoubleModal;@@ -88,6 +89,7 @@ use super::noun_countability::NounCountability;use super::number_suffix_capitalization::NumberSuffixCapitalization;use super::of_course::OfCourse;use super::on_floor::OnFloor;+use super::once_or_twice::OnceOrTwice;use super::one_and_the_same::OneAndTheSame;use super::open_the_light::OpenTheLight;use super::ought_to_be::OughtToBe;@@ -114,6 +116,7 @@ use super::sentence_capitalization::SentenceCapitalization;use super::shoot_oneself_in_the_foot::ShootOneselfInTheFoot;use super::simple_past_to_past_participle::SimplePastToPastParticiple;use super::since_duration::SinceDuration;+use super::something_is::SomethingIs;use super::somewhat_something::SomewhatSomething;use super::sought_after::SoughtAfter;use super::spaces::Spaces;@@ -126,15 +129,19 @@ use super::the_my::TheMy;use super::then_than::ThenThan;use super::thing_think::ThingThink;use super::though_thought::ThoughThought;+use super::throw_away::ThrowAway;use super::throw_rubbish::ThrowRubbish;+use super::to_adverb::ToAdverb;use super::to_two_too::ToTwoToo;use super::touristic::Touristic;use super::unclosed_quotes::UnclosedQuotes;use super::update_place_names::UpdatePlaceNames;use super::use_genitive::UseGenitive;use super::very_unique::VeryUnique;+use super::vice_versa::ViceVersa;use super::was_aloud::WasAloud;use super::way_too_adjective::WayTooAdjective;+use super::well_educated::WellEducated;use super::whereas::Whereas;use super::widely_accepted::WidelyAccepted;use super::win_prize::WinPrize;@@ -447,6 +454,7 @@ impl LintGroup {insert_struct_rule!(CurrencyPlacement, true);insert_expr_rule!(Dashes, true);insert_expr_rule!(DespiteOf, true);+ insert_expr_rule!(Didnt, true);insert_struct_rule!(DiscourseMarkers, true);insert_expr_rule!(DotInitialisms, true);insert_expr_rule!(DoubleModal, true);@@ -498,6 +506,7 @@ impl LintGroup {insert_struct_rule!(NumberSuffixCapitalization, true);insert_struct_rule!(OfCourse, true);insert_expr_rule!(OnFloor, true);+ insert_expr_rule!(OnceOrTwice, true);insert_expr_rule!(OneAndTheSame, true);insert_expr_rule!(OpenCompounds, true);insert_expr_rule!(OpenTheLight, true);@@ -522,6 +531,7 @@ impl LintGroup {insert_expr_rule!(ShootOneselfInTheFoot, true);insert_expr_rule!(SimplePastToPastParticiple, true);insert_expr_rule!(SinceDuration, true);+ insert_expr_rule!(SomethingIs, true);insert_expr_rule!(SomewhatSomething, true);insert_expr_rule!(SoughtAfter, true);insert_struct_rule!(Spaces, true);@@ -533,15 +543,19 @@ impl LintGroup {insert_expr_rule!(ThenThan, true);insert_expr_rule!(ThingThink, true);insert_expr_rule!(ThoughThought, true);+ insert_expr_rule!(ThrowAway, true);insert_struct_rule!(ThrowRubbish, true);+ insert_expr_rule!(ToAdverb, true);insert_struct_rule!(ToTwoToo, true);insert_expr_rule!(Touristic, true);insert_struct_rule!(UnclosedQuotes, true);insert_expr_rule!(UpdatePlaceNames, true);insert_expr_rule!(UseGenitive, false);+ insert_expr_rule!(ViceVersa, true);insert_expr_rule!(VeryUnique, true);insert_expr_rule!(WasAloud, true);insert_expr_rule!(WayTooAdjective, true);+ insert_expr_rule!(WellEducated, true);insert_expr_rule!(Whereas, true);insert_expr_rule!(WidelyAccepted, true);insert_expr_rule!(WinPrize, true);diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rsindex 162c668a5..3dc420b45 100644--- a/harper-core/src/linting/mod.rs+++ b/harper-core/src/linting/mod.rs@@ -29,6 +29,7 @@ mod criteria_phenomena;mod currency_placement;mod dashes;mod despite_of;+mod didnt;mod discourse_markers;mod dot_initialisms;mod double_modal;@@ -96,6 +97,7 @@ mod noun_verb_confusion;mod number_suffix_capitalization;mod of_course;mod on_floor;+mod once_or_twice;mod one_and_the_same;mod open_compounds;mod open_the_light;@@ -126,6 +128,7 @@ mod sentence_capitalization;mod shoot_oneself_in_the_foot;mod simple_past_to_past_participle;mod since_duration;+mod something_is;mod somewhat_something;mod sought_after;mod spaces;@@ -140,15 +143,19 @@ mod the_my;mod then_than;mod thing_think;mod though_thought;+mod throw_away;mod throw_rubbish;+mod to_adverb;mod to_two_too;mod touristic;mod unclosed_quotes;mod update_place_names;mod use_genitive;mod very_unique;+mod vice_versa;mod was_aloud;mod way_too_adjective;+mod well_educated;mod whereas;mod widely_accepted;mod win_prize;@@ -181,6 +188,7 @@ pub use criteria_phenomena::CriteriaPhenomena;pub use currency_placement::CurrencyPlacement;pub use dashes::Dashes;pub use despite_of::DespiteOf;+pub use didnt::Didnt;pub use discourse_markers::DiscourseMarkers;pub use dot_initialisms::DotInitialisms;pub use double_modal::DoubleModal;@@ -240,6 +248,7 @@ pub use noun_verb_confusion::NounVerbConfusion;pub use number_suffix_capitalization::NumberSuffixCapitalization;pub use of_course::OfCourse;pub use on_floor::OnFloor;+pub use once_or_twice::OnceOrTwice;pub use one_and_the_same::OneAndTheSame;pub use open_the_light::OpenTheLight;pub use ought_to_be::OughtToBe;@@ -265,6 +274,7 @@ pub use sentence_capitalization::SentenceCapitalization;pub use shoot_oneself_in_the_foot::ShootOneselfInTheFoot;pub use simple_past_to_past_participle::SimplePastToPastParticiple;pub use since_duration::SinceDuration;+pub use something_is::SomethingIs;pub use somewhat_something::SomewhatSomething;pub use sought_after::SoughtAfter;pub use spaces::Spaces;@@ -279,15 +289,19 @@ pub use the_my::TheMy;pub use then_than::ThenThan;pub use thing_think::ThingThink;pub use though_thought::ThoughThought;+pub use throw_away::ThrowAway;pub use throw_rubbish::ThrowRubbish;+pub use to_adverb::ToAdverb;pub use to_two_too::ToTwoToo;pub use touristic::Touristic;pub use unclosed_quotes::UnclosedQuotes;pub use update_place_names::UpdatePlaceNames;pub use use_genitive::UseGenitive;pub use very_unique::VeryUnique;+pub use vice_versa::ViceVersa;pub use was_aloud::WasAloud;pub use way_too_adjective::WayTooAdjective;+pub use well_educated::WellEducated;pub use whereas::Whereas;pub use widely_accepted::WidelyAccepted;pub use win_prize::WinPrize;diff --git a/harper-core/src/linting/once_or_twice.rs b/harper-core/src/linting/once_or_twice.rsnew file mode 100644index 000000000..231460b56--- /dev/null+++ b/harper-core/src/linting/once_or_twice.rs@@ -0,0 +1,303 @@+use crate::CharStringExt;+use crate::Token;+use crate::expr::{Expr, SequenceExpr};++use super::{ExprLinter, Lint, LintKind, Suggestion};++pub struct OnceOrTwice {+ expr: Box<dyn Expr>,+}++impl Default for OnceOrTwice {+ fn default() -> Self {+ let pattern = SequenceExpr::aco("once")+ .then_whitespace()+ .t_aco("a")+ .then_whitespace()+ .t_aco("twice");++ Self {+ expr: Box::new(pattern),+ }+ }+}++impl ExprLinter for OnceOrTwice {+ fn expr(&self) -> &dyn Expr {+ self.expr.as_ref()+ }++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {+ let article = matched_tokens.iter().find(|token| {+ token.kind.is_word() && token.span.get_content(source).eq_ignore_ascii_case_str("a")+ })?;++ let span = article.span;+ let original = span.get_content(source);++ Some(Lint {+ span,+ lint_kind: LintKind::WordChoice,+ suggestions: vec![Suggestion::replace_with_match_case_str("or", original)],+ message: "Did you mean “or”?".to_owned(),+ priority: 31,+ })+ }++ fn description(&self) -> &'static str {+ "Detects the mistaken phrase `once a twice` and suggests `once or twice`."+ }+}++#[cfg(test)]+mod tests {+ use crate::linting::tests::{assert_no_lints, assert_suggestion_result};++ use super::OnceOrTwice;++ #[test]+ fn corrects_once_a_twice() {+ assert_suggestion_result(+ "He wants to do it once a twice a month.",+ OnceOrTwice::default(),+ "He wants to do it once or twice a month.",+ );+ }++ #[test]+ fn allows_once_or_twice() {+ assert_no_lints(+ "He wants to do it once or twice a month.",+ OnceOrTwice::default(),+ );+ }++ #[test]+ fn corrects_once_a_twice_sentence_start() {+ assert_suggestion_result(+ "Once a twice, we gathered for coffee.",+ OnceOrTwice::default(),+ "Once or twice, we gathered for coffee.",+ );+ }++ #[test]+ fn corrects_once_a_twice_uppercase() {+ assert_suggestion_result(+ "ONCE A TWICE WE MET.",+ OnceOrTwice::default(),+ "ONCE OR TWICE WE MET.",+ );+ }++ #[test]+ fn corrects_once_a_twice_mixed_case() {+ assert_suggestion_result(+ "once a Twice sounds odd.",+ OnceOrTwice::default(),+ "once or Twice sounds odd.",+ );+ }++ #[test]+ fn corrects_once_a_twice_with_exclamation() {+ assert_suggestion_result(+ "Let's do it once a twice!",+ OnceOrTwice::default(),+ "Let's do it once or twice!",+ );+ }++ #[test]+ fn corrects_once_a_twice_with_question_mark() {+ assert_suggestion_result(+ "You really tried once a twice?",+ OnceOrTwice::default(),+ "You really tried once or twice?",+ );+ }++ #[test]+ fn corrects_once_a_twice_inside_quotes() {+ assert_suggestion_result(+ "He said, \"once a twice\" without thinking.",+ OnceOrTwice::default(),+ "He said, \"once or twice\" without thinking.",+ );+ }++ #[test]+ fn corrects_once_a_twice_with_comma() {+ assert_suggestion_result(+ "We planned it once a twice, but never finished.",+ OnceOrTwice::default(),+ "We planned it once or twice, but never finished.",+ );+ }++ #[test]+ fn corrects_once_a_twice_with_parentheses() {+ assert_suggestion_result(+ "Try it (just once a twice) before judging.",+ OnceOrTwice::default(),+ "Try it (just once or twice) before judging.",+ );+ }++ #[test]+ fn corrects_once_a_twice_after_colon() {+ assert_suggestion_result(+ "My answer is simple: once a twice is too many.",+ OnceOrTwice::default(),+ "My answer is simple: once or twice is too many.",+ );+ }++ #[test]+ fn corrects_once_a_twice_with_double_space() {+ assert_suggestion_result(+ "We tested once a twice before launch.",+ OnceOrTwice::default(),+ "We tested once or twice before launch.",+ );+ }++ #[test]+ fn corrects_once_a_twice_before_semicolon() {+ assert_suggestion_result(+ "They tried once a twice; it still failed.",+ OnceOrTwice::default(),+ "They tried once or twice; it still failed.",+ );+ }++ #[test]+ fn corrects_once_a_twice_newline_split() {+ assert_suggestion_result(+ "We met once a twice\nwhen the cafe was quiet.",+ OnceOrTwice::default(),+ "We met once or twice\nwhen the cafe was quiet.",+ );+ }++ #[test]+ fn corrects_once_a_twice_with_tab() {+ assert_suggestion_result(+ "Schedule it once a twice\tfor testing.",+ OnceOrTwice::default(),+ "Schedule it once or twice\tfor testing.",+ );+ }++ #[test]+ fn corrects_once_a_twice_multiple_sentences() {+ assert_suggestion_result(+ "Do it once a twice. Then rest.",+ OnceOrTwice::default(),+ "Do it once or twice. Then rest.",+ );+ }++ #[test]+ fn corrects_once_a_twice_before_period() {+ assert_suggestion_result(+ "He rehearsed once a twice.",+ OnceOrTwice::default(),+ "He rehearsed once or twice.",+ );+ }++ #[test]+ fn corrects_once_a_twice_with_trailing_space() {+ assert_suggestion_result(+ "Practice once a twice .",+ OnceOrTwice::default(),+ "Practice once or twice .",+ );+ }++ #[test]+ fn corrects_once_a_twice_before_dash() {+ assert_suggestion_result(+ "He called once a twice—no response.",+ OnceOrTwice::default(),+ "He called once or twice—no response.",+ );+ }++ #[test]+ fn corrects_once_a_twice_around_em_dash() {+ assert_suggestion_result(+ "She visits once a twice—maybe thrice.",+ OnceOrTwice::default(),+ "She visits once or twice—maybe thrice.",+ );+ }++ #[test]+ fn corrects_once_a_twice_before_quote() {+ assert_suggestion_result(+ "We heard once a twice, \"she's late.\"",+ OnceOrTwice::default(),+ "We heard once or twice, \"she's late.\"",+ );+ }++ #[test]+ fn corrects_once_a_twice_all_caps_sentence() {+ assert_suggestion_result(+ "DO IT ONCE A TWICE RIGHT NOW!",+ OnceOrTwice::default(),+ "DO IT ONCE OR TWICE RIGHT NOW!",+ );+ }++ #[test]+ fn allows_once_a_time_story() {+ assert_no_lints("Once a time, in a distant land...", OnceOrTwice::default());+ }++ #[test]+ fn allows_once_a_week_routine() {+ assert_no_lints("We meet once a week to sync up.", OnceOrTwice::default());+ }++ #[test]+ fn allows_once_a_while_phrase() {+ assert_no_lints(+ "Check in every once a while to stay updated.",+ OnceOrTwice::default(),+ );+ }++ #[test]+ fn allows_once_or_twice_uppercase() {+ assert_no_lints("ONCE OR TWICE, WE MADE IT WORK.", OnceOrTwice::default());+ }++ #[test]+ fn allows_twice_without_once() {+ assert_no_lints(+ "We only managed it twice this year.",+ OnceOrTwice::default(),+ );+ }++ #[test]+ fn allows_once_and_twice_separated() {+ assert_no_lints("Once I tried; twice I failed.", OnceOrTwice::default());+ }++ #[test]+ fn allows_oncemisatypo() {+ assert_no_lints("oncemisatypo appears once a line.", OnceOrTwice::default());+ }++ #[test]+ fn allows_spaced_words() {+ assert_no_lints(+ "We say once at twice distance to be safe.",+ OnceOrTwice::default(),+ );+ }+}diff --git a/harper-core/src/linting/phrase_corrections/mod.rs b/harper-core/src/linting/phrase_corrections/mod.rsindex 0660d8972..ad790f72f 100644--- a/harper-core/src/linting/phrase_corrections/mod.rs+++ b/harper-core/src/linting/phrase_corrections/mod.rs@@ -752,6 +752,13 @@ pub fn lint_group() -> LintGroup {"Corrects non-standard variants of `low-hanging fruit`.",LintKind::Usage),+ "ManagerialReins" => (+ ["managerial reigns"],+ ["managerial reins"],+ "Swap in `reins` when talking about control of a team or project.",+ "Corrects the eggcorn `managerial reigns` to the idiomatic `managerial reins`.",+ LintKind::Eggcorn+ ),"Monumentous" => (["monumentous"],["momentous", "monumental"],diff --git a/harper-core/src/linting/phrase_corrections/tests.rs b/harper-core/src/linting/phrase_corrections/tests.rsindex 57a706154..15f8b43ea 100644--- a/harper-core/src/linting/phrase_corrections/tests.rs+++ b/harper-core/src/linting/phrase_corrections/tests.rs@@ -1,5 +1,5 @@use crate::linting::tests::{- assert_lint_count, assert_nth_suggestion_result, assert_suggestion_result,+ assert_lint_count, assert_no_lints, assert_nth_suggestion_result, assert_suggestion_result,assert_top3_suggestion_result,};@@ -907,6 +907,88 @@ fn corrects_low_hanging_fruits_space() {)}+// ManagerialReins+#[test]+fn fixes_managerial_reigns_basic() {+ assert_suggestion_result(+ "She grabbed the managerial reigns during the crisis.",+ lint_group(),+ "She grabbed the managerial reins during the crisis.",+ );+}++#[test]+fn fixes_managerial_reigns_sentence_start() {+ assert_suggestion_result(+ "Managerial reigns are never easy to hand over.",+ lint_group(),+ "Managerial reins are never easy to hand over.",+ );+}++#[test]+fn fixes_managerial_reigns_with_article() {+ assert_suggestion_result(+ "The managerial reigns belong to Carla now.",+ lint_group(),+ "The managerial reins belong to Carla now.",+ );+}++#[test]+fn fixes_managerial_reigns_with_comma() {+ assert_suggestion_result(+ "By winter, he held the managerial reigns, and morale improved.",+ lint_group(),+ "By winter, he held the managerial reins, and morale improved.",+ );+}++#[test]+fn fixes_managerial_reigns_question() {+ assert_suggestion_result(+ "Who will hold the managerial reigns after April?",+ lint_group(),+ "Who will hold the managerial reins after April?",+ );+}++#[test]+fn fixes_managerial_reigns_in_quotes() {+ assert_suggestion_result(+ "\"managerial reigns\" showed up in the draft notes.",+ lint_group(),+ "\"managerial reins\" showed up in the draft notes.",+ );+}++#[test]+fn counts_managerial_reigns_error() {+ assert_lint_count(+ "They debated who should manage the managerial reigns for the quarter.",+ lint_group(),+ 1,+ );+}++#[test]+fn counts_managerial_reigns_caps() {+ assert_lint_count("Their memo shouted MANAGERIAL REIGNS.", lint_group(), 1);+}++#[test]+fn allows_managerial_reins_correct() {+ assert_no_lints(+ "He kept the managerial reins despite the reshuffle.",+ lint_group(),+ );+}++#[test]+fn allows_reigns_without_managerial() {+ assert_no_lints("Legends of ancient reigns filled the museum.", lint_group());+}+// Monumentous#[test]fn detect_monumentous_atomic() {diff --git a/harper-core/src/linting/something_is.rs b/harper-core/src/linting/something_is.rsnew file mode 100644index 000000000..414ee057d--- /dev/null+++ b/harper-core/src/linting/something_is.rs@@ -0,0 +1,152 @@+use crate::expr::{Expr, SequenceExpr};+use crate::patterns::WordSet;+use crate::{Token, TokenKind};++use super::{ExprLinter, Lint, LintKind, Suggestion};++pub struct SomethingIs {+ expr: Box<dyn Expr>,+}++impl Default for SomethingIs {+ fn default() -> Self {+ let forms = WordSet::new(&["somethings", "anythings", "everythings", "nothings"]);++ let expr = SequenceExpr::default()+ .then(forms)+ .t_ws()+ .then_optional(SequenceExpr::default().then_one_or_more_adverbs().t_ws())+ .then_kind_any(&[TokenKind::is_verb_progressive_form]);++ Self {+ expr: Box::new(expr),+ }+ }+}++impl ExprLinter for SomethingIs {+ fn expr(&self) -> &dyn Expr {+ self.expr.as_ref()+ }++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {+ let offender = matched_tokens.first()?;+ let original = offender.span.get_content(source);+ let stem_len = original.len().checked_sub(1)?;+ let stem = original[..stem_len].to_vec();++ let mut contraction = stem.clone();+ contraction.extend(['\'', 's']);++ let mut expanded = stem;+ expanded.push(' ');+ expanded.extend(['i', 's']);++ Some(Lint {+ span: offender.span,+ lint_kind: LintKind::WordChoice,+ suggestions: vec![+ Suggestion::replace_with_match_case(contraction, original),+ Suggestion::replace_with_match_case(expanded, original),+ ],+ message: "Prefer the contraction or full `is` rather than pluralizing this pronoun."+ .into(),+ priority: 31,+ })+ }++ fn description(&self) -> &str {+ "Flags forms like `somethings` before progressive verbs and suggests using `something's` or `something is`."+ }+}++#[cfg(test)]+mod tests {+ use super::SomethingIs;+ use crate::linting::tests::{+ assert_lint_count, assert_no_lints, assert_nth_suggestion_result, assert_suggestion_result,+ };++ #[test]+ fn fixes_somethings_going() {+ assert_suggestion_result(+ "Somethings going well today.",+ SomethingIs::default(),+ "Something's going well today.",+ );+ }++ #[test]+ fn fixes_anythings_happening() {+ assert_suggestion_result(+ "Anythings happening tonight?",+ SomethingIs::default(),+ "Anything's happening tonight?",+ );+ }++ #[test]+ fn fixes_everythings_working() {+ assert_suggestion_result(+ "Everythings working smoothly.",+ SomethingIs::default(),+ "Everything's working smoothly.",+ );+ }++ #[test]+ fn fixes_nothings_changing() {+ assert_suggestion_result(+ "Nothings changing around here.",+ SomethingIs::default(),+ "Nothing's changing around here.",+ );+ }++ #[test]+ fn fixes_with_adverb() {+ assert_suggestion_result(+ "Somethings really happening now.",+ SomethingIs::default(),+ "Something's really happening now.",+ );+ }++ #[test]+ fn fixes_uppercase() {+ assert_suggestion_result(+ "SOMETHINGS HAPPENING NOW!",+ SomethingIs::default(),+ "SOMETHING'S HAPPENING NOW!",+ );+ }++ #[test]+ fn offers_is_expansion() {+ assert_nth_suggestion_result(+ "Somethings going wrong.",+ SomethingIs::default(),+ "Something is going wrong.",+ 1,+ );+ }++ #[test]+ fn no_lint_when_contracted() {+ assert_no_lints("Something's going well today.", SomethingIs::default());+ }++ #[test]+ fn no_lint_when_plural_noun() {+ assert_lint_count(+ "Somethings in the attic kept us awake.",+ SomethingIs::default(),+ 0,+ );+ }++ #[test]+ fn no_lint_at_sentence_end() {+ assert_no_lints("Somethings.", SomethingIs::default());+ }+}diff --git a/harper-core/src/linting/throw_away.rs b/harper-core/src/linting/throw_away.rsnew file mode 100644index 000000000..102527ac3--- /dev/null+++ b/harper-core/src/linting/throw_away.rs@@ -0,0 +1,137 @@+use crate::{+ Token,+ expr::{Expr, SequenceExpr},+ linting::{ExprLinter, Lint, LintKind, Suggestion},+};++pub struct ThrowAway {+ expr: Box<dyn Expr>,+}++impl Default for ThrowAway {+ fn default() -> Self {+ let expr = SequenceExpr::default()+ .t_aco("through")+ .t_ws()+ .t_aco("away");++ Self {+ expr: Box::new(expr),+ }+ }+}++impl ExprLinter for ThrowAway {+ fn expr(&self) -> &dyn Expr {+ self.expr.as_ref()+ }++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {+ let typo = matched_tokens.first()?;+ let original = typo.span.get_content(source);++ Some(Lint {+ span: typo.span,+ lint_kind: LintKind::Typo,+ suggestions: vec![Suggestion::replace_with_match_case_str("throw", original)],+ message: "Use `throw away` when you want to discard something.".to_string(),+ priority: 60,+ })+ }++ fn description(&self) -> &str {+ "Finds the typo `through away` and suggests `throw away` instead."+ }+}++#[cfg(test)]+mod tests {+ use super::ThrowAway;+ use crate::linting::tests::{assert_lint_count, assert_no_lints, assert_suggestion_result};++ #[test]+ fn corrects_simple_case() {+ assert_suggestion_result(+ "We through away the old code.",+ ThrowAway::default(),+ "We throw away the old code.",+ );+ }++ #[test]+ fn corrects_sentence_start_capital() {+ assert_suggestion_result(+ "Through away this document when you're done.",+ ThrowAway::default(),+ "Throw away this document when you're done.",+ );+ }++ #[test]+ fn corrects_all_caps_instance() {+ assert_suggestion_result(+ "Please THROUGH AWAY THE TRASH.",+ ThrowAway::default(),+ "Please THROW AWAY THE TRASH.",+ );+ }++ #[test]+ fn corrects_with_extra_whitespace() {+ assert_suggestion_result(+ "We through away the leftovers.",+ ThrowAway::default(),+ "We throw away the leftovers.",+ );+ }++ #[test]+ fn does_not_flag_throw_away() {+ assert_no_lints(+ "They throw away the packaging every time.",+ ThrowAway::default(),+ );+ }++ #[test]+ fn does_not_flag_through_tunnel() {+ assert_no_lints(+ "They walked through the tunnel away from danger.",+ ThrowAway::default(),+ );+ }++ #[test]+ fn flags_multiple_occurrences() {+ assert_lint_count(+ "We through away the forks and through away the spoons.",+ ThrowAway::default(),+ 2,+ );+ }++ #[test]+ fn does_not_flag_thorough() {+ assert_no_lints(+ "She gave the room a thorough, away-from-home cleaning.",+ ThrowAway::default(),+ );+ }++ #[test]+ fn corrects_with_contraction() {+ assert_suggestion_result(+ "Don't through away your shot.",+ ThrowAway::default(),+ "Don't throw away your shot.",+ );+ }++ #[test]+ fn does_not_flag_spread_words() {+ assert_no_lints(+ "They pushed through as the crowd moved away.",+ ThrowAway::default(),+ );+ }+}diff --git a/harper-core/src/linting/to_adverb.rs b/harper-core/src/linting/to_adverb.rsnew file mode 100644index 000000000..b8283bae4--- /dev/null+++ b/harper-core/src/linting/to_adverb.rs@@ -0,0 +1,170 @@+use harper_brill::UPOS;++use crate::expr::{Expr, OwnedExprExt, SequenceExpr};+use crate::patterns::{UPOSSet, WordSet};+use crate::{Span, Token};++use super::{ExprLinter, Lint, LintKind, Suggestion};++const AMBIGUOUS_ADVERBS: &[&str] = &["just", "not"];++pub struct ToAdverb {+ expr: Box<dyn Expr>,+}++impl Default for ToAdverb {+ fn default() -> Self {+ let expr = SequenceExpr::default()+ .t_aco("to")+ .t_ws()+ .then(UPOSSet::new(&[UPOS::ADV]).or(WordSet::new(AMBIGUOUS_ADVERBS)))+ .t_ws()+ .t_aco("to")+ .t_ws()+ .then_verb();++ Self {+ expr: Box::new(expr),+ }+ }+}++impl ExprLinter for ToAdverb {+ fn expr(&self) -> &dyn Expr {+ self.expr.as_ref()+ }++ fn match_to_lint(&self, tokens: &[Token], source: &[char]) -> Option<Lint> {+ let first_to = tokens.first()?;+ let second_to_idx = 4;+ let second_to = tokens.get(second_to_idx)?;++ let adverb_idx = 2;++ let adverb = tokens.get(adverb_idx)?;++ let span = Span::new(first_to.span.start, second_to.span.end);+ let keep_first_variant = source[first_to.span.start..adverb.span.end].to_vec();+ let drop_first_variant = source[adverb.span.start..second_to.span.end].to_vec();++ if keep_first_variant.is_empty() || drop_first_variant.is_empty() {+ return None;+ }++ Some(Lint {+ span,+ lint_kind: LintKind::Miscellaneous,+ suggestions: vec![+ Suggestion::ReplaceWith(keep_first_variant),+ Suggestion::ReplaceWith(drop_first_variant),+ ],+ message: "Remove the repeated `to` in this infinitive.".to_owned(),+ priority: 40,+ })+ }++ fn description(&self) -> &'static str {+ "Flags duplicated `to` around certain adverbs (e.g. `to never to`) and offers fixes that keep only one `to`."+ }+}++#[cfg(test)]+mod tests {+ use super::ToAdverb;+ use crate::linting::tests::{+ assert_lint_count, assert_nth_suggestion_result, assert_suggestion_count,+ assert_suggestion_result,+ };++ #[test]+ fn corrects_to_never_to() {+ assert_suggestion_result(+ "Tom has decided to never to do that again.",+ ToAdverb::default(),+ "Tom has decided to never do that again.",+ );+ }++ #[test]+ fn alternative_moves_adverb() {+ assert_nth_suggestion_result(+ "Tom has decided to never to do that again.",+ ToAdverb::default(),+ "Tom has decided never to do that again.",+ 1,+ );+ }++ #[test]+ fn corrects_to_maybe_to() {+ assert_suggestion_result(+ "The next step is to maybe to take a language class.",+ ToAdverb::default(),+ "The next step is to maybe take a language class.",+ );+ }++ #[test]+ fn corrects_to_not_to() {+ assert_suggestion_result(+ "He tells the monitor to not to collect anything.",+ ToAdverb::default(),+ "He tells the monitor to not collect anything.",+ );+ }++ #[test]+ fn corrects_to_just_to() {+ assert_suggestion_result(+ "She told me to just to keep the peace.",+ ToAdverb::default(),+ "She told me to just keep the peace.",+ );+ }++ #[test]+ fn corrects_to_really_to() {+ assert_suggestion_result(+ "They plan to really to push the release.",+ ToAdverb::default(),+ "They plan to really push the release.",+ );+ }++ #[test]+ fn offers_two_suggestions() {+ assert_suggestion_count(+ "He agreed to probably to lead the effort.",+ ToAdverb::default(),+ 2,+ );+ }++ #[test]+ fn allows_single_to_with_adverb() {+ assert_lint_count("He wants to always win the match.", ToAdverb::default(), 0);+ }++ #[test]+ fn corrects_to_quickly_to() {+ assert_suggestion_result(+ "They hoped to quickly to solve it.",+ ToAdverb::default(),+ "They hoped to quickly solve it.",+ );+ }++ #[test]+ fn ignores_missing_verb_after_second_to() {+ assert_lint_count("We tried to eventually to.", ToAdverb::default(), 0);+ }++ #[test]+ fn handles_capitalized_to() {+ assert_suggestion_result(+ "To Always to succeed is the goal.",+ ToAdverb::default(),+ "To Always succeed is the goal.",+ );+ }+}diff --git a/harper-core/src/linting/vice_versa.rs b/harper-core/src/linting/vice_versa.rsnew file mode 100644index 000000000..1da3eb6c0--- /dev/null+++ b/harper-core/src/linting/vice_versa.rs@@ -0,0 +1,205 @@+use crate::expr::{Expr, SequenceExpr};+use crate::linting::{ExprLinter, Lint, LintKind, Suggestion};+use crate::{Token, TokenStringExt};++fn matches_hyphen(token: &Token, _source: &[char]) -> bool {+ token.kind.is_hyphen()+}++fn replacement_for(template: &[char]) -> Vec<char> {+ let mut replacement = "vice versa".chars().collect::<Vec<_>>();++ let mut has_upper = false;+ let mut has_lower = false;+ let mut first_alpha_upper = None;++ for ch in template.iter().copied() {+ if !ch.is_alphabetic() {+ continue;+ }++ has_upper |= ch.is_uppercase();+ has_lower |= ch.is_lowercase();++ if first_alpha_upper.is_none() {+ first_alpha_upper = Some(ch.is_uppercase());+ }+ }++ if has_upper && !has_lower {+ for ch in replacement.iter_mut() {+ if ch.is_alphabetic() {+ *ch = ch.to_ascii_uppercase();+ }+ }++ return replacement;+ }++ if !has_upper {+ return replacement;+ }++ if first_alpha_upper.unwrap_or(false) {+ let mut capitalized_first = false;++ for ch in replacement.iter_mut() {+ if !ch.is_alphabetic() {+ continue;+ }++ if !capitalized_first {+ *ch = ch.to_ascii_uppercase();+ capitalized_first = true;+ } else {+ *ch = ch.to_ascii_lowercase();+ }+ }++ return replacement;+ }++ for ch in replacement.iter_mut() {+ if ch.is_alphabetic() {+ *ch = ch.to_ascii_lowercase();+ }+ }++ replacement+}++pub struct ViceVersa {+ expr: Box<dyn Expr>,+}++impl Default for ViceVersa {+ fn default() -> Self {+ let expr = SequenceExpr::word_set(&["vice", "vise"])+ .then(matches_hyphen)+ .then_optional(SequenceExpr::aco("a").then(matches_hyphen))+ .then(SequenceExpr::aco("versa"));++ Self {+ expr: Box::new(expr),+ }+ }+}++impl ExprLinter for ViceVersa {+ fn expr(&self) -> &dyn Expr {+ self.expr.as_ref()+ }++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {+ let span = matched_tokens.span()?;+ let template = span.get_content(source);++ Some(Lint {+ span,+ lint_kind: LintKind::Punctuation,+ suggestions: vec![Suggestion::ReplaceWith(replacement_for(template))],+ message: "The expression \"vice versa\" is spelled without hyphens.".to_owned(),+ priority: 60,+ })+ }++ fn description(&self) -> &str {+ "Recommends writing ‘vice versa’ without hyphens."+ }+}++#[cfg(test)]+mod tests {+ use super::ViceVersa;+ use crate::linting::tests::{assert_lint_count, assert_suggestion_result};++ #[test]+ fn corrects_basic_hyphenated() {+ assert_suggestion_result(+ "We swapped the arguments vice-versa this time.",+ ViceVersa::default(),+ "We swapped the arguments vice versa this time.",+ );+ }++ #[test]+ fn corrects_leading_capitalization() {+ assert_suggestion_result(+ "Vice-Versa, the movie, was interesting.",+ ViceVersa::default(),+ "Vice versa, the movie, was interesting.",+ );+ }++ #[test]+ fn corrects_all_caps() {+ assert_suggestion_result(+ "They agreed VICE-VERSA on the clause.",+ ViceVersa::default(),+ "They agreed VICE VERSA on the clause.",+ );+ }++ #[test]+ fn corrects_with_extra_a() {+ assert_suggestion_result(+ "The logic works vice-a-versa as well.",+ ViceVersa::default(),+ "The logic works vice versa as well.",+ );+ }++ #[test]+ fn corrects_vise_variant() {+ assert_suggestion_result(+ "The rule applies vise-versa too.",+ ViceVersa::default(),+ "The rule applies vice versa too.",+ );+ }++ #[test]+ fn corrects_vise_extra_a_variant() {+ assert_suggestion_result(+ "The rule applies Vise-A-Versa too.",+ ViceVersa::default(),+ "The rule applies Vice versa too.",+ );+ }++ #[test]+ fn corrects_with_trailing_suffix() {+ assert_suggestion_result(+ "That was a vice-versa-like transformation.",+ ViceVersa::default(),+ "That was a vice versa-like transformation.",+ );+ }++ #[test]+ fn allows_correct_spelling() {+ assert_lint_count(+ "We swapped the arguments vice versa this time.",+ ViceVersa::default(),+ 0,+ );+ }++ #[test]+ fn allows_sentence_case() {+ assert_lint_count(+ "Vice versa, the movie, was interesting.",+ ViceVersa::default(),+ 0,+ );+ }++ #[test]+ fn does_not_flag_unrelated_words() {+ assert_lint_count(+ "Their service-versa mapping was custom.",+ ViceVersa::default(),+ 0,+ );+ }+}diff --git a/harper-core/src/linting/well_educated.rs b/harper-core/src/linting/well_educated.rsnew file mode 100644index 000000000..dea7ac667--- /dev/null+++ b/harper-core/src/linting/well_educated.rs@@ -0,0 +1,149 @@+use crate::{+ Token, TokenStringExt,+ expr::{Expr, SequenceExpr},+ patterns::{WhitespacePattern, WordSet},+};++use super::{ExprLinter, Lint, LintKind, Suggestion};++pub struct WellEducated {+ expr: Box<dyn Expr>,+}++impl Default for WellEducated {+ fn default() -> Self {+ let combined = WordSet::new(&["good-educated"]);++ let separated = SequenceExpr::default()+ .t_aco("good")+ .then_optional(WhitespacePattern)+ .then_hyphen()+ .then_optional(WhitespacePattern)+ .t_aco("educated");++ let expr =+ SequenceExpr::default().then_any_of(vec![Box::new(combined), Box::new(separated)]);++ Self {+ expr: Box::new(expr),+ }+ }+}++impl ExprLinter for WellEducated {+ fn expr(&self) -> &dyn Expr {+ self.expr.as_ref()+ }++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {+ let span = matched_tokens.span()?;+ let original = span.get_content(source);++ Some(Lint {+ span,+ lint_kind: LintKind::Miscellaneous,+ suggestions: vec![Suggestion::replace_with_match_case(+ "well-educated".chars().collect(),+ original,+ )],+ message: "Prefer `well-educated` for this compound.".into(),+ priority: 35,+ })+ }++ fn description(&self) -> &'static str {+ "Replaces `good-educated` with the accepted compound `well-educated`."+ }+}++#[cfg(test)]+mod tests {+ use super::WellEducated;+ use crate::linting::tests::{assert_lint_count, assert_suggestion_result};++ #[test]+ fn corrects_simple_sentence() {+ assert_suggestion_result(+ "She is good-educated.",+ WellEducated::default(),+ "She is well-educated.",+ );+ }++ #[test]+ fn corrects_in_clause() {+ assert_suggestion_result(+ "The panel found him good-educated and articulate.",+ WellEducated::default(),+ "The panel found him well-educated and articulate.",+ );+ }++ #[test]+ fn corrects_with_modifier() {+ assert_suggestion_result(+ "They considered her very good-educated for her age.",+ WellEducated::default(),+ "They considered her very well-educated for her age.",+ );+ }++ #[test]+ fn corrects_all_caps() {+ assert_suggestion_result(+ "Their mentors are GOOD-EDUCATED leaders.",+ WellEducated::default(),+ "Their mentors are WELL-EDUCATED leaders.",+ );+ }++ #[test]+ fn corrects_title_case() {+ assert_suggestion_result(+ "The report lauded Good-Educated Candidates.",+ WellEducated::default(),+ "The report lauded Well-Educated Candidates.",+ );+ }++ #[test]+ fn corrects_with_quotes() {+ assert_suggestion_result(+ "He called them \"good-educated\" professionals.",+ WellEducated::default(),+ "He called them \"well-educated\" professionals.",+ );+ }++ #[test]+ fn corrects_split_tokens() {+ assert_suggestion_result(+ "Their children are good - educated despite the odds.",+ WellEducated::default(),+ "Their children are well-educated despite the odds.",+ );+ }++ #[test]+ fn allows_well_educated() {+ assert_lint_count("She is well-educated.", WellEducated::default(), 0);+ }++ #[test]+ fn allows_good_education_phrase() {+ assert_lint_count(+ "They received a good education.",+ WellEducated::default(),+ 0,+ );+ }++ #[test]+ fn allows_good_to_be_educated() {+ assert_lint_count(+ "It is good to be educated about local history.",+ WellEducated::default(),+ 0,+ );+ }+}