Skip to content

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

feat(core): create rule that fixes it's -> its (#1622)

Elijah Potter2d358c24d0b7
diff --git a/harper-core/dictionary.dict b/harper-core/dictionary.dict
index eba078426..8a247d012 100644
--- a/harper-core/dictionary.dict
+++ b/harper-core/dictionary.dict
@@ -17041,7 +17041,8 @@ chartreuse/NJg
charwoman/Ng
charwomen/9
chary/J^>p
-chase/~NVgZGd>S
+chase/~NVgZGd>
+chases/~V
chaser/~Ng
chasm/NgS
chassis/~Ng09 # singular and plural
diff --git a/harper-core/src/document.rs b/harper-core/src/document.rs
index 27fa138b0..23f37bb1f 100644
--- a/harper-core/src/document.rs
+++ b/harper-core/src/document.rs
@@ -159,7 +159,7 @@ impl Document {
let mut found_meta = dictionary.get_word_metadata(word_source).cloned();
if let Some(inner) = &mut found_meta {
- inner.pos_tag = token_tags[i];
+ inner.pos_tag = token_tags[i].or_else(|| inner.infer_pos_tag());
inner.np_member = Some(np_flags[i]);
}
diff --git a/harper-core/src/linting/its_possessive.rs b/harper-core/src/linting/its_possessive.rs
new file mode 100644
index 000000000..6f970e7ff
--- /dev/null
+++ b/harper-core/src/linting/its_possessive.rs
@@ -0,0 +1,295 @@
+use std::sync::Arc;
+
+use harper_brill::UPOS;
+
+use crate::Token;
+use crate::expr::AnchorStart;
+use crate::expr::Expr;
+use crate::expr::ExprMap;
+use crate::expr::OwnedExprExt;
+use crate::expr::SequenceExpr;
+use crate::patterns::UPOSSet;
+use crate::patterns::WordSet;
+
+use super::{ExprLinter, Lint, LintKind, Suggestion};
+
+pub struct ItsPossessive {
+ expr: Box<dyn Expr>,
+ map: Arc<ExprMap<usize>>,
+}
+
+impl Default for ItsPossessive {
+ fn default() -> Self {
+ let mut map = ExprMap::default();
+
+ let adj_term = SequenceExpr::default()
+ .t_ws()
+ .then(UPOSSet::new(&[UPOS::ADJ]));
+
+ let mid_sentence = SequenceExpr::default()
+ .then(UPOSSet::new(&[UPOS::VERB, UPOS::ADP]))
+ .t_ws()
+ .t_aco("it's")
+ .then_optional(adj_term)
+ .t_ws()
+ .then(
+ UPOSSet::new(&[UPOS::NOUN, UPOS::PROPN]).or(|tok: &Token, _: &[char]| {
+ tok.kind.as_number().is_some_and(|n| n.suffix.is_some())
+ }),
+ );
+
+ map.insert(mid_sentence, 2);
+
+ let start_of_sentence = SequenceExpr::default()
+ .then(AnchorStart)
+ .t_aco("it's")
+ .t_ws()
+ .then(UPOSSet::new(&[UPOS::ADJ, UPOS::NOUN, UPOS::PROPN]))
+ .t_ws()
+ .then_unless(UPOSSet::new(&[UPOS::PART, UPOS::NOUN, UPOS::PRON]));
+
+ map.insert(start_of_sentence, 0);
+
+ let special = SequenceExpr::aco("it's")
+ .t_ws()
+ .then(WordSet::new(&["various", "many"]));
+
+ map.insert(special, 0);
+
+ let map = Arc::new(map);
+
+ Self {
+ expr: Box::new(map.clone()),
+ map,
+ }
+ }
+}
+
+impl ExprLinter for ItsPossessive {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
+ }
+
+ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
+ let offending_idx = self.map.lookup(0, matched_tokens, source).unwrap();
+ let span = matched_tokens[*offending_idx].span;
+
+ Some(Lint {
+ span,
+ lint_kind: LintKind::Agreement,
+ suggestions: vec![Suggestion::replace_with_match_case_str(
+ "its",
+ span.get_content(source),
+ )],
+ message: "Prefer the possessive pronoun `its` here to denote ownership.".to_string(),
+ priority: 31,
+ })
+ }
+
+ fn description(&self) -> &'static str {
+ "In English, possessive pronouns never take an apostrophe. Use `its` to show ownership (e.g. “its texture”) and avoid confusing it with `it's`, which always means “it is” or “it has.”"
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::linting::tests::{assert_lint_count, assert_no_lints, assert_suggestion_result};
+
+ use super::ItsPossessive;
+
+ #[test]
+ fn corrects_its_various() {
+ assert_suggestion_result(
+ "I like it's various colors.",
+ ItsPossessive::default(),
+ "I like its various colors.",
+ );
+ }
+
+ #[test]
+ fn fixes_inspiration() {
+ assert_suggestion_result(
+ "I would just put `Orthography` and it's various function implementations in their own `orthography.rs` file.",
+ ItsPossessive::default(),
+ "I would just put `Orthography` and its various function implementations in their own `orthography.rs` file.",
+ );
+ }
+
+ #[test]
+ fn engine_lost_its_compression() {
+ assert_lint_count(
+ "The engine lost it's compression.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn admired_sculpture_for_its_intricacy() {
+ assert_suggestion_result(
+ "I admired the sculpture for it's intricacy.",
+ ItsPossessive::default(),
+ "I admired the sculpture for its intricacy.",
+ );
+ }
+
+ #[test]
+ fn paris_is_known_for_its_architecture() {
+ assert_lint_count(
+ "Paris is known for it's architecture.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn plain_sentence_with_apostrophe_s() {
+ assert_suggestion_result(
+ "It's benefits are numerous.",
+ ItsPossessive::default(),
+ "Its benefits are numerous.",
+ );
+ }
+
+ #[test]
+ fn device_reached_its_100th_cycle() {
+ assert_lint_count(
+ "The device reached it's 100th cycle.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn oddly_its_wheels_misaligned() {
+ assert_lint_count(
+ "Oddly, it's wheels were misaligned.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn leaking_oil_constant_issue() {
+ assert_lint_count("It's leaking oil constantly.", ItsPossessive::default(), 0);
+ }
+
+ #[test]
+ fn fiftyth_anniversary() {
+ assert_lint_count(
+ "The company celebrated it's 50th anniversary.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn second_attempt() {
+ assert_lint_count("He failed it's 2nd attempt.", ItsPossessive::default(), 1);
+ }
+
+ #[test]
+ fn third_iteration() {
+ assert_lint_count(
+ "The program finished it's 3rd iteration.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn tenth_milestone() {
+ assert_lint_count(
+ "They reached it's 10th milestone.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn seventh_chapter() {
+ assert_lint_count(
+ "The novel lost it's 7th chapter.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn fifth_version() {
+ assert_lint_count(
+ "Software updated to it's 5th version.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn eighth_floor() {
+ assert_lint_count(
+ "Elevator stopped at it's 8th floor.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn twelfth_episode() {
+ assert_lint_count(
+ "Series ended it's 12th episode.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn fourth_draft() {
+ assert_lint_count("He completed it's 4th draft.", ItsPossessive::default(), 1);
+ }
+
+ #[test]
+ fn ninth_revision() {
+ assert_lint_count(
+ "The report saved it's 9th revision.",
+ ItsPossessive::default(),
+ 1,
+ );
+ }
+
+ #[test]
+ fn allows_hard_to_tell() {
+ assert_no_lints("It's hard to tell from here.", ItsPossessive::default());
+ }
+
+ #[test]
+ fn allows_illegible() {
+ assert_no_lints(
+ "When you write in cursive, its illegible",
+ ItsPossessive::default(),
+ );
+ }
+
+ #[test]
+ fn allows_good_practice() {
+ assert_no_lints(
+ "it's good practice to review the general settings",
+ ItsPossessive::default(),
+ );
+ }
+
+ #[test]
+ fn allows_understandable() {
+ assert_no_lints(
+ "It's understandable that you'd feel the weight of responsibility.",
+ ItsPossessive::default(),
+ );
+ }
+
+ #[test]
+ fn allows_insincere() {
+ assert_no_lints(
+ "But feel free to omit it if you feel it's insincere.",
+ ItsPossessive::default(),
+ );
+ }
+}
diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rs
index 1e4482203..334725884 100644
--- a/harper-core/src/linting/lint_group.rs
+++ b/harper-core/src/linting/lint_group.rs
@@ -50,6 +50,7 @@ use super::hyphenate_number_day::HyphenateNumberDay;
use super::in_on_the_cards::InOnTheCards;
use super::inflected_verb_after_to::InflectedVerbAfterTo;
use super::its_contraction::ItsContraction;
+use super::its_possessive::ItsPossessive;
use super::left_right_hand::LeftRightHand;
use super::less_worse::LessWorse;
use super::lets_confusion::LetsConfusion;
@@ -399,6 +400,7 @@ impl LintGroup {
insert_expr_rule!(BoringWords, false);
insert_struct_rule!(CapitalizePersonalPronouns, true);
insert_expr_rule!(ChockFull, true);
+ insert_struct_rule!(ItsPossessive, true);
insert_expr_rule!(DoubleModal, true);
insert_expr_rule!(MissingPreposition, true);
insert_struct_rule!(DiscourseMarkers, true);
diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rs
index e36132fc7..ca2c8b65f 100644
--- a/harper-core/src/linting/mod.rs
+++ b/harper-core/src/linting/mod.rs
@@ -49,6 +49,7 @@ mod initialisms;
mod it_is;
mod it_would_be;
mod its_contraction;
+mod its_possessive;
mod left_right_hand;
mod less_worse;
mod lets_confusion;
@@ -164,6 +165,7 @@ pub use in_on_the_cards::InOnTheCards;
pub use inflected_verb_after_to::InflectedVerbAfterTo;
pub use initialism_linter::InitialismLinter;
pub use its_contraction::ItsContraction;
+pub use its_possessive::ItsPossessive;
pub use left_right_hand::LeftRightHand;
pub use less_worse::LessWorse;
pub use lets_confusion::LetsConfusion;
diff --git a/harper-core/src/linting/possessive_noun.rs b/harper-core/src/linting/possessive_noun.rs
index d27ae710e..263a17a3e 100644
--- a/harper-core/src/linting/possessive_noun.rs
+++ b/harper-core/src/linting/possessive_noun.rs
@@ -37,7 +37,7 @@ where
.then_noun();
let exceptions = SequenceExpr::default()
- .t_any()
+ .then_unless(|tok: &Token, _: &[char]| tok.kind.is_demonstrative_determiner())
.t_any()
.then_unless(WordSet::new(&["flags", "checks", "catches", "you"]))
.t_any()
diff --git a/harper-core/src/word_metadata.rs b/harper-core/src/word_metadata.rs
index 8a8a2333e..735430b4f 100644
--- a/harper-core/src/word_metadata.rs
+++ b/harper-core/src/word_metadata.rs
@@ -3,6 +3,7 @@ use is_macro::Is;
use itertools::Itertools;
use paste::paste;
use serde::{Deserialize, Serialize};
+use smallvec::SmallVec;
use strum::{EnumCount, VariantArray};
use strum_macros::{Display, EnumCount, EnumString, VariantArray};
@@ -99,6 +100,65 @@ macro_rules! generate_metadata_queries {
}
impl WordMetadata {
+ /// If there is only one possible interpretation of the metadata, infer its UPOS tag.
+ pub fn infer_pos_tag(&self) -> Option<UPOS> {
+ // If an explicit POS tag exists, return it immediately.
+ if let Some(pos) = self.pos_tag {
+ return Some(pos);
+ }
+
+ // Collect all possible POS tags from metadata
+ let mut candidates = SmallVec::<[UPOS; 14]>::with_capacity(14);
+
+ if self.is_proper_noun() {
+ candidates.push(UPOS::PROPN);
+ }
+
+ if self.is_pronoun() {
+ candidates.push(UPOS::PRON);
+ }
+ if self.is_noun() {
+ candidates.push(UPOS::NOUN);
+ }
+ if self.is_verb() {
+ // Distinguish auxiliary verbs
+ if let Some(data) = &self.verb {
+ if data.is_auxiliary == Some(true) {
+ candidates.push(UPOS::AUX);
+ } else {
+ candidates.push(UPOS::VERB);
+ }
+ } else {
+ candidates.push(UPOS::VERB);
+ }
+ }
+ if self.is_adjective() {
+ candidates.push(UPOS::ADJ);
+ }
+ if self.is_adverb() {
+ candidates.push(UPOS::ADV);
+ }
+ if self.is_conjunction() {
+ candidates.push(UPOS::CCONJ);
+ }
+ if self.is_determiner() {
+ candidates.push(UPOS::DET);
+ }
+ if self.preposition {
+ candidates.push(UPOS::ADP);
+ }
+
+ // Remove duplicates
+ candidates.sort();
+ candidates.dedup();
+
+ if candidates.len() == 1 {
+ candidates.first().copied()
+ } else {
+ None
+ }
+ }
+
/// Produce a copy of `self` with the known properties of `other` set.
pub fn or(&self, other: &Self) -> Self {
macro_rules! merge {
diff --git a/harper-core/tests/text/linters/Difficult sentences.snap.yml b/harper-core/tests/text/linters/Difficult sentences.snap.yml
index 95e22173a..a06899264 100644
--- a/harper-core/tests/text/linters/Difficult sentences.snap.yml
+++ b/harper-core/tests/text/linters/Difficult sentences.snap.yml
@@ -316,6 +316,15 @@ Suggest:
+Lint: Agreement (31 priority)
+Message: |
+ 426 | What's the time? – It's quarter to four in the afternoon (or 3:45 pm).
+ | ^~~~ Prefer the possessive pronoun `its` here to denote ownership.
+Suggest:
+ - Replace with: “Its”
+
+
+
Lint: Spelling (63 priority)
Message: |
443 | With their reputation on the line, they decided to fire their PR team.
diff --git a/harper-core/tests/text/linters/Swear.snap.yml b/harper-core/tests/text/linters/Swear.snap.yml
index 2a0045ecc..e8ee7bb31 100644
--- a/harper-core/tests/text/linters/Swear.snap.yml
+++ b/harper-core/tests/text/linters/Swear.snap.yml
@@ -1,12 +1,3 @@
-Lint: Miscellaneous (10 priority)
-Message: |
- 3 | This documents tests that different forms/variations of swears are tagged as such.
- | ^~~~~~~~~ Use an apostrophe and `s` to form a noun’s possessive.
-Suggest:
- - Replace with: “document's”
-
-
-
Lint: Miscellaneous (63 priority)
Message: |
7 | One turd, two turds.
diff --git a/harper-core/tests/text/linters/The Constitution of the United States.snap.yml b/harper-core/tests/text/linters/The Constitution of the United States.snap.yml
index 94d6b629d..d40e27834 100644
--- a/harper-core/tests/text/linters/The Constitution of the United States.snap.yml
+++ b/harper-core/tests/text/linters/The Constitution of the United States.snap.yml
@@ -775,6 +775,16 @@ Message: |
+Lint: Agreement (31 priority)
+Message: |
+ 312 | on Imports or Exports, except what may be absolutely necessary for executing
+ 313 | it's inspection Laws: and the net Produce of all Duties and Imposts, laid by
+ | ^~~~ Prefer the possessive pronoun `its` here to denote ownership.
+Suggest:
+ - Replace with: “its”
+
+
+
Lint: Spelling (63 priority)
Message: |
315 | United States; and all such Laws shall be subject to the Revision and Controul
diff --git a/harper-core/tests/text/linters/The Great Gatsby.snap.yml b/harper-core/tests/text/linters/The Great Gatsby.snap.yml
index eefb521a8..be728c29e 100644
--- a/harper-core/tests/text/linters/The Great Gatsby.snap.yml
+++ b/harper-core/tests/text/linters/The Great Gatsby.snap.yml
@@ -4200,6 +4200,17 @@ Suggest:
+Lint: WordChoice (54 priority)
+Message: |
+ 2995 | of emotion. I think that voice held him most, with its fluctuating, feverish
+ | ^~~ Use `it's` (short for `it has` or `it is`) here, not the possessive `its`.
+ 2996 | warmth, because it couldn’t be over-dreamed—that voice was a deathless song.
+Suggest:
+ - Replace with: “it's”
+ - Replace with: “it has”
+
+
+
Lint: Readability (127 priority)
Message: |
3020 | short of being news. Contemporary legends such as the “underground pipe-line to
@@ -7442,6 +7453,14 @@ Message: |
+Lint: Miscellaneous (31 priority)
+Message: |
+ 5780 | entirely justified. It was all very careless and confused. They were careless
+ | ^~~~~ You may be missing a preposition here.
+ 5781 | people, Tom and Daisy—they smashed up things and creatures and then retreated
+
+
+
Lint: Style (31 priority)
Message: |
5780 | entirely justified. It was all very careless and confused. They were careless