Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(core): add several new rules
Elijah Pottercf5c58b8c3d4
diff --git a/harper-core/src/linting/ask_no_preposition.rs b/harper-core/src/linting/ask_no_preposition.rsnew file mode 100644index 000000000..1db5676d5--- /dev/null+++ b/harper-core/src/linting/ask_no_preposition.rs@@ -0,0 +1,196 @@+use crate::{+ Span, Token, TokenStringExt,+ linting::{Lint, LintKind, PatternLinter, Suggestion},+ patterns::{Pattern, SequencePattern, WordSet},+};++pub struct AskNoPreposition {+ pattern: Box<dyn Pattern>,+}++impl Default for AskNoPreposition {+ fn default() -> Self {+ let verbs = WordSet::new(&[+ "ask", "asks", "asked", "asking", "tell", "tells", "told", "telling",+ ]);++ let objs = WordSet::new(&["me", "you", "him", "her", "it", "us", "them", "one"]);++ let pattern = SequencePattern::default()+ .then(verbs)+ .then_whitespace()+ .then_exact_word("to")+ .then_whitespace()+ .then(objs);++ Self {+ pattern: Box::new(pattern),+ }+ }+}++impl PatternLinter for AskNoPreposition {+ fn pattern(&self) -> &dyn Pattern {+ self.pattern.as_ref()+ }++ fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {+ if toks.len() < 5 {+ return None;+ }++ let verb = toks[0].span.get_content_string(src).to_lowercase();+ let span = Span::new(toks[2].span.start, toks[3].span.end);++ Some(Lint {+ span,+ lint_kind: LintKind::WordChoice,+ suggestions: vec![Suggestion::ReplaceWith(Vec::new())],+ message: format!(+ "The verb `to {verb} someone` should not be preceded by the preposition “to”."+ ),+ priority: 63,+ })+ }++ fn description(&self) -> &str {+ "Identifies sequences like `ask to us` or `tell to him` and recommends removing the superfluous “to”."+ }+}++#[cfg(test)]+mod tests {+ use super::AskNoPreposition;+ use crate::linting::tests::{assert_lint_count, assert_suggestion_result};++ #[test]+ fn flags_ask() {+ assert_suggestion_result(+ "Nora asked to us about the concert lineup.",+ AskNoPreposition::default(),+ "Nora asked us about the concert lineup.",+ );+ }++ #[test]+ fn flags_tell() {+ assert_suggestion_result(+ "Please tell to him the results promptly.",+ AskNoPreposition::default(),+ "Please tell him the results promptly.",+ );+ }++ #[test]+ fn ignores_correct_usage() {+ assert_lint_count(+ "She asked her mentor a difficult question.",+ AskNoPreposition::default(),+ 0,+ );+ }++ #[test]+ fn flags_ask_us() {+ assert_suggestion_result(+ "Can you ask to us for directions?",+ AskNoPreposition::default(),+ "Can you ask us for directions?",+ );+ }++ #[test]+ fn flags_asks_him() {+ assert_suggestion_result(+ "Julia asks to him every morning about the report.",+ AskNoPreposition::default(),+ "Julia asks him every morning about the report.",+ );+ }++ #[test]+ fn flags_asked_me() {+ assert_suggestion_result(+ "They asked to me why I left early.",+ AskNoPreposition::default(),+ "They asked me why I left early.",+ );+ }++ #[test]+ fn flags_told_one() {+ assert_suggestion_result(+ "The guide told to one the secret path.",+ AskNoPreposition::default(),+ "The guide told one the secret path.",+ );+ }++ #[test]+ fn flags_telling_it() {+ assert_suggestion_result(+ "She is telling to it with gentle words.",+ AskNoPreposition::default(),+ "She is telling it with gentle words.",+ );+ }++ #[test]+ fn flags_tells_them() {+ assert_suggestion_result(+ "He tells to them stories at night.",+ AskNoPreposition::default(),+ "He tells them stories at night.",+ );+ }++ #[test]+ fn flags_telling_him() {+ assert_suggestion_result(+ "I was telling to him the latest news.",+ AskNoPreposition::default(),+ "I was telling him the latest news.",+ );+ }++ #[test]+ fn flags_asking_you() {+ assert_suggestion_result(+ "Someone is asking to you for help.",+ AskNoPreposition::default(),+ "Someone is asking you for help.",+ );+ }++ #[test]+ fn ignores_ask_question() {+ assert_lint_count(+ "Ask her the question directly.",+ AskNoPreposition::default(),+ 0,+ );+ }++ #[test]+ fn ignores_told_to_leave() {+ assert_lint_count(+ "He was told to leave immediately.",+ AskNoPreposition::default(),+ 0,+ );+ }++ #[test]+ fn ignores_tell_us() {+ assert_lint_count("Please tell us your name.", AskNoPreposition::default(), 0);+ }++ #[test]+ fn ignores_ask_about() {+ assert_lint_count(+ "They asked about the schedule.",+ AskNoPreposition::default(),+ 0,+ );+ }+}diff --git a/harper-core/src/linting/else_possessive.rs b/harper-core/src/linting/else_possessive.rsnew file mode 100644index 000000000..f86285a42--- /dev/null+++ b/harper-core/src/linting/else_possessive.rs@@ -0,0 +1,96 @@+use crate::{+ Span, Token, TokenStringExt,+ linting::{Lint, LintKind, PatternLinter, Suggestion},+ patterns::{Pattern, SequencePattern, WordSet},+};++pub struct ElsePossessive {+ pattern: Box<dyn Pattern>,+}++impl Default for ElsePossessive {+ fn default() -> Self {+ let pronouns = WordSet::new(&[+ "somebody",+ "someone",+ "anybody",+ "anyone",+ "everybody",+ "everyone",+ "nobody",+ "noone",+ ]);++ let pattern = SequencePattern::default()+ .then(pronouns)+ .then_whitespace()+ .t_aco("elses");++ Self {+ pattern: Box::new(pattern),+ }+ }+}++impl PatternLinter for ElsePossessive {+ fn pattern(&self) -> &dyn Pattern {+ self.pattern.as_ref()+ }++ fn match_to_lint(&self, toks: &[Token], _src: &[char]) -> Option<Lint> {+ let offender = toks.last()?;+ Some(Lint {+ span: offender.span,+ lint_kind: LintKind::Miscellaneous,+ suggestions: vec![Suggestion::ReplaceWith("else's".chars().collect())],+ message: "Add the missing possessive apostrophe: use `else’s`.".to_owned(),+ priority: 60,+ })+ }++ fn description(&self) -> &str {+ "Detects missing apostrophes in phrases like `someone elses book` and suggests the correct possessive form `else’s`."+ }+}++#[cfg(test)]+mod tests {+ use super::ElsePossessive;+ use crate::linting::tests::{assert_lint_count, assert_suggestion_result};++ #[test]+ fn fixes_someone_elses() {+ assert_suggestion_result(+ "It's someone elses problem.",+ ElsePossessive::default(),+ "It's someone else's problem.",+ );+ }++ #[test]+ fn fixes_anybody_elses() {+ assert_suggestion_result(+ "Was that anybody elses idea?",+ ElsePossessive::default(),+ "Was that anybody else's idea?",+ );+ }++ #[test]+ fn fixes_everyone_elses() {+ assert_suggestion_result(+ "He echoed everyone elses concerns.",+ ElsePossessive::default(),+ "He echoed everyone else's concerns.",+ );+ }++ #[test]+ fn ignores_correct_form() {+ assert_lint_count(+ "She borrowed someone else's notes.",+ ElsePossessive::default(),+ 0,+ );+ }+}diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rsindex 7c12af2e4..668c20995 100644--- a/harper-core/src/linting/lint_group.rs+++ b/harper-core/src/linting/lint_group.rs@@ -13,6 +13,7 @@ use serde::{Deserialize, Serialize};use super::adjective_of_a::AdjectiveOfA;use super::an_a::AnA;+use super::ask_no_preposition::AskNoPreposition;use super::avoid_curses::AvoidCurses;use super::back_in_the_day::BackInTheDay;use super::boring_words::BoringWords;@@ -25,6 +26,7 @@ use super::correct_number_suffix::CorrectNumberSuffix;use super::despite_of::DespiteOf;use super::dot_initialisms::DotInitialisms;use super::ellipsis_length::EllipsisLength;+use super::else_possessive::ElsePossessive;use super::expand_time_shorthands::ExpandTimeShorthands;use super::first_aid_kit::FirstAidKit;use super::for_noun::ForNoun;@@ -42,7 +44,9 @@ use super::long_sentences::LongSentences;use super::merge_words::MergeWords;use super::modal_of::ModalOf;use super::multiple_sequential_pronouns::MultipleSequentialPronouns;+use super::nail_on_the_head::NailOnTheHead;use super::nobody::Nobody;+use super::nominal_wants::NominalWants;use super::number_suffix_capitalization::NumberSuffixCapitalization;use super::of_course::OfCourse;use super::one_and_the_same::OneAndTheSame;@@ -70,6 +74,7 @@ use super::use_genitive::UseGenitive;use super::was_aloud::WasAloud;use super::whereas::Whereas;use super::widely_accepted::WidelyAccepted;+use super::win_prize::WinPrize;use super::wordpress_dotcom::WordPressDotcom;use super::{CurrencyPlacement, Linter, NoOxfordComma, OxfordComma};use super::{Lint, PatternLinter};@@ -310,6 +315,11 @@ impl LintGroup {insert_pattern_rule!(BoringWords, false);insert_struct_rule!(CapitalizePersonalPronouns, true);insert_pattern_rule!(ChockFull, true);+ insert_struct_rule!(NailOnTheHead, true);+ insert_struct_rule!(NominalWants, true);+ insert_struct_rule!(ElsePossessive, true);+ insert_pattern_rule!(WinPrize, true);+ insert_pattern_rule!(AskNoPreposition, true);insert_struct_rule!(CommaFixes, true);insert_struct_rule!(CompoundNouns, true);insert_pattern_rule!(Confident, true);diff --git a/harper-core/src/linting/lint_kind.rs b/harper-core/src/linting/lint_kind.rsindex a88717138..96e41033e 100644--- a/harper-core/src/linting/lint_kind.rs+++ b/harper-core/src/linting/lint_kind.rs@@ -17,9 +17,9 @@ pub enum LintKind {Enhancement,Readability,WordChoice,+ Punctuation,#[default]Miscellaneous,- Punctuation,}impl LintKind {diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rsindex a1ac7707e..5caca75a6 100644--- a/harper-core/src/linting/mod.rs+++ b/harper-core/src/linting/mod.rs@@ -4,6 +4,7 @@mod adjective_of_a;mod an_a;+mod ask_no_preposition;mod avoid_curses;mod back_in_the_day;mod boring_words;@@ -19,6 +20,7 @@ mod dashes;mod despite_of;mod dot_initialisms;mod ellipsis_length;+mod else_possessive;mod expand_time_shorthands;mod first_aid_kit;mod for_noun;@@ -43,8 +45,10 @@ mod merge_linters;mod merge_words;mod modal_of;mod multiple_sequential_pronouns;+mod nail_on_the_head;mod no_oxford_comma;mod nobody;+mod nominal_wants;mod number_suffix_capitalization;mod of_course;mod one_and_the_same;@@ -75,10 +79,12 @@ mod use_genitive;mod was_aloud;mod whereas;mod widely_accepted;+mod win_prize;mod wordpress_dotcom;pub use adjective_of_a::AdjectiveOfA;pub use an_a::AnA;+pub use ask_no_preposition::AskNoPreposition;pub use avoid_curses::AvoidCurses;pub use back_in_the_day::BackInTheDay;pub use boring_words::BoringWords;@@ -113,6 +119,7 @@ pub use map_phrase_linter::MapPhraseLinter;pub use merge_words::MergeWords;pub use modal_of::ModalOf;pub use multiple_sequential_pronouns::MultipleSequentialPronouns;+pub use nail_on_the_head::NailOnTheHead;pub use no_oxford_comma::NoOxfordComma;pub use nobody::Nobody;pub use number_suffix_capitalization::NumberSuffixCapitalization;@@ -142,6 +149,7 @@ pub use use_genitive::UseGenitive;pub use was_aloud::WasAloud;pub use whereas::Whereas;pub use widely_accepted::WidelyAccepted;+pub use win_prize::WinPrize;pub use wordpress_dotcom::WordPressDotcom;use crate::{Document, LSend};diff --git a/harper-core/src/linting/nail_on_the_head.rs b/harper-core/src/linting/nail_on_the_head.rsnew file mode 100644index 000000000..b205f4b05--- /dev/null+++ b/harper-core/src/linting/nail_on_the_head.rs@@ -0,0 +1,94 @@+use crate::{+ Token,+ linting::{Lint, LintKind, PatternLinter, Suggestion},+ patterns::{Pattern, SequencePattern, WordSet},+};++pub struct NailOnTheHead {+ pattern: Box<dyn Pattern>,+}++impl Default for NailOnTheHead {+ fn default() -> Self {+ let mis = WordSet::new(&["hat", "had", "hit", "hid"]);+ let pattern = SequencePattern::default()+ .t_aco("nail")+ .then_whitespace()+ .t_aco("on")+ .then_whitespace()+ .t_aco("the")+ .then_whitespace()+ .then(mis);+ Self {+ pattern: Box::new(pattern),+ }+ }+}++impl PatternLinter for NailOnTheHead {+ fn pattern(&self) -> &dyn Pattern {+ self.pattern.as_ref()+ }++ fn match_to_lint(&self, toks: &[Token], _src: &[char]) -> Option<Lint> {+ let offender = toks.last()?;+ Some(Lint {+ span: offender.span,+ lint_kind: LintKind::Miscellaneous,+ suggestions: vec![Suggestion::ReplaceWith("head".chars().collect())],+ message: "Did you mean `head`?".to_owned(),+ priority: 45,+ })+ }++ fn description(&self) -> &str {+ "Replaces hat/had/hit/hid in the idiom `nail on the head` with `head`."+ }+}++#[cfg(test)]+mod tests {+ use super::NailOnTheHead;+ use crate::linting::tests::{assert_lint_count, assert_suggestion_result};++ #[test]+ fn fix_hat() {+ assert_suggestion_result(+ "She hit the nail on the hat.",+ NailOnTheHead::default(),+ "She hit the nail on the head.",+ );+ }++ #[test]+ fn fix_had() {+ assert_suggestion_result(+ "You really put the nail on the had with that comment.",+ NailOnTheHead::default(),+ "You really put the nail on the head with that comment.",+ );+ }++ #[test]+ fn fix_hit() {+ assert_suggestion_result(+ "They hit the nail on the hit regarding our problem.",+ NailOnTheHead::default(),+ "They hit the nail on the head regarding our problem.",+ );+ }++ #[test]+ fn fix_hid() {+ assert_suggestion_result(+ "The article nails the nail on the hid this time.",+ NailOnTheHead::default(),+ "The article nails the nail on the head this time.",+ );+ }++ #[test]+ fn ignore_correct() {+ assert_lint_count("She hit the nail on the head.", NailOnTheHead::default(), 0);+ }+}diff --git a/harper-core/src/linting/nominal_wants.rs b/harper-core/src/linting/nominal_wants.rsnew file mode 100644index 000000000..fd560b70d--- /dev/null+++ b/harper-core/src/linting/nominal_wants.rs@@ -0,0 +1,81 @@+use crate::{+ Token,+ linting::{Lint, LintKind, PatternLinter, Suggestion},+ patterns::{Pattern, SequencePattern, WordSet},+};++pub struct NominalWants {+ pattern: Box<dyn Pattern>,+}++impl Default for NominalWants {+ fn default() -> Self {+ let miss = WordSet::new(&["wont", "wonts"]);+ let pattern = SequencePattern::default()+ .then_nominal()+ .then_whitespace()+ .then(miss);+ Self {+ pattern: Box::new(pattern),+ }+ }+}++impl PatternLinter for NominalWants {+ fn pattern(&self) -> &dyn Pattern {+ self.pattern.as_ref()+ }++ fn match_to_lint(&self, toks: &[Token], _src: &[char]) -> Option<Lint> {+ let offender = toks.last()?;+ Some(Lint {+ span: offender.span,+ lint_kind: LintKind::Miscellaneous,+ suggestions: vec![Suggestion::ReplaceWith("wants".chars().collect())],+ message: "Did you mean `wants`?".to_owned(),+ priority: 55,+ })+ }++ fn description(&self) -> &str {+ "Replaces the typo `wont`/`wonts` after a nominal."+ }+}++#[cfg(test)]+mod tests {+ use super::NominalWants;+ use crate::linting::tests::{assert_lint_count, assert_suggestion_result};++ #[test]+ fn fixes_he_wonts() {+ assert_suggestion_result(+ "He wonts to join us.",+ NominalWants::default(),+ "He wants to join us.",+ );+ }++ #[test]+ fn fixes_it_wont() {+ assert_suggestion_result(+ "It wont to move forward.",+ NominalWants::default(),+ "It wants to move forward.",+ );+ }++ #[test]+ fn fixes_she_wont() {+ assert_suggestion_result(+ "She wont to leave early.",+ NominalWants::default(),+ "She wants to leave early.",+ );+ }++ #[test]+ fn ignores_correct_usage() {+ assert_lint_count("He wants to help.", NominalWants::default(), 0);+ }+}diff --git a/harper-core/src/linting/win_prize.rs b/harper-core/src/linting/win_prize.rsnew file mode 100644index 000000000..416f9e9fa--- /dev/null+++ b/harper-core/src/linting/win_prize.rs@@ -0,0 +1,108 @@+use crate::{+ Token,+ linting::{Lint, LintKind, PatternLinter, Suggestion},+ patterns::{Pattern, SequencePattern, WordSet},+};++pub struct WinPrize {+ pattern: Box<dyn Pattern>,+}++impl Default for WinPrize {+ fn default() -> Self {+ let verbs = WordSet::new(&["win", "wins", "won", "winning"]);+ let miss = WordSet::new(&["price", "prices", "prise", "prises"]);++ let pattern = SequencePattern::default()+ .then(verbs)+ .then_whitespace()+ .then_determiner()+ .then_whitespace()+ .then(miss);++ Self {+ pattern: Box::new(pattern),+ }+ }+}++impl PatternLinter for WinPrize {+ fn pattern(&self) -> &dyn Pattern {+ self.pattern.as_ref()+ }++ fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {+ let candidate = toks.last()?;+ let raw = candidate.span.get_content_string(src).to_lowercase();+ let repl = match raw.as_str() {+ "price" | "prise" => "prize",+ "prices" | "prises" => "prizes",+ _ => return None,+ };++ Some(Lint {+ span: candidate.span,+ lint_kind: LintKind::Miscellaneous,+ suggestions: vec![Suggestion::ReplaceWith(repl.chars().collect())],+ message: format!("Perhaps you meant `{repl}`, the word for an award."),+ priority: 50,+ })+ }++ fn description(&self) -> &str {+ "Catches the mix-up between `price`/`prise` and `prize` after the verb `win`."+ }+}++#[cfg(test)]+mod tests {+ use super::WinPrize;+ use crate::linting::tests::{+ assert_lint_count, assert_suggestion_result, assert_top3_suggestion_result,+ };++ #[test]+ fn fix_price_singular() {+ assert_suggestion_result(+ "Lena won a price in the coding marathon.",+ WinPrize::default(),+ "Lena won a prize in the coding marathon.",+ );+ }++ #[test]+ fn fix_price_plural() {+ assert_top3_suggestion_result(+ "Our team won the prices announced yesterday.",+ WinPrize::default(),+ "Our team won the prizes announced yesterday.",+ );+ }++ #[test]+ fn fix_prise_singular() {+ assert_suggestion_result(+ "He finally won the prise he'd dreamed of.",+ WinPrize::default(),+ "He finally won the prize he'd dreamed of.",+ );+ }++ #[test]+ fn fix_prise_plural() {+ assert_suggestion_result(+ "The inventors won several prises at the expo.",+ WinPrize::default(),+ "The inventors won several prizes at the expo.",+ );+ }++ #[test]+ fn ignore_correct_prize() {+ assert_lint_count(+ "Miranda won the grand prize last year.",+ WinPrize::default(),+ 0,+ );+ }+}