Skip to content

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

fix: don't close compound if open is in dictionary (#1347)

Andrew Dunbare5703ae716c0
diff --git a/harper-core/src/linting/compound_nouns/compound_noun_after_det_adj.rs b/harper-core/src/linting/compound_nouns/compound_noun_after_det_adj.rs
index 6be3eedce..a962f617c 100644
--- a/harper-core/src/linting/compound_nouns/compound_noun_after_det_adj.rs
+++ b/harper-core/src/linting/compound_nouns/compound_noun_after_det_adj.rs
@@ -1,10 +1,10 @@
use crate::{
CharStringExt, TokenStringExt,
linting::PatternLinter,
- patterns::{All, SplitCompoundWord},
+ patterns::{All, MergeableWords},
};
-use super::{Lint, LintKind, Suggestion, create_split_pattern, is_content_word};
+use super::{Lint, LintKind, Suggestion, is_content_word, predicate};
use crate::{
Lrc, Token,
@@ -14,7 +14,7 @@ use crate::{
/// Two adjacent words separated by whitespace that if joined would be a valid noun.
pub struct CompoundNounAfterDetAdj {
pattern: Box<dyn Pattern>,
- split_pattern: Lrc<SplitCompoundWord>,
+ split_pattern: Lrc<MergeableWords>,
}
// This heuristic identifies potential compound nouns by:
@@ -38,7 +38,9 @@ impl Default for CompoundNounAfterDetAdj {
.then_whitespace()
.then(is_content_word);
- let split_pattern = create_split_pattern();
+ let split_pattern = Lrc::new(MergeableWords::new(|meta_closed, meta_open| {
+ predicate(meta_closed, meta_open)
+ }));
let mut pattern = All::default();
pattern.add(Box::new(context_pattern));
diff --git a/harper-core/src/linting/compound_nouns/compound_noun_after_possessive.rs b/harper-core/src/linting/compound_nouns/compound_noun_after_possessive.rs
index f1e73d2f4..655ebe64b 100644
--- a/harper-core/src/linting/compound_nouns/compound_noun_after_possessive.rs
+++ b/harper-core/src/linting/compound_nouns/compound_noun_after_possessive.rs
@@ -1,10 +1,10 @@
use crate::{
CharStringExt, Lrc, TokenStringExt,
linting::PatternLinter,
- patterns::{All, SplitCompoundWord},
+ patterns::{All, MergeableWords},
};
-use super::{Lint, LintKind, Suggestion, create_split_pattern, is_content_word};
+use super::{Lint, LintKind, Suggestion, is_content_word, predicate};
use crate::{
Token,
@@ -20,7 +20,7 @@ use crate::{
/// harper-core/src/linting/pronoun_contraction/should_contract.rs
pub struct CompoundNounAfterPossessive {
pattern: Box<dyn Pattern>,
- split_pattern: Lrc<SplitCompoundWord>,
+ split_pattern: Lrc<MergeableWords>,
}
impl Default for CompoundNounAfterPossessive {
@@ -32,7 +32,9 @@ impl Default for CompoundNounAfterPossessive {
.t_ws()
.then(is_content_word);
- let split_pattern = create_split_pattern();
+ let split_pattern = Lrc::new(MergeableWords::new(|meta_closed, meta_open| {
+ predicate(meta_closed, meta_open)
+ }));
let mut pattern = All::default();
diff --git a/harper-core/src/linting/compound_nouns/compound_noun_before_aux_verb.rs b/harper-core/src/linting/compound_nouns/compound_noun_before_aux_verb.rs
index 48f6c19ce..bb6d557c8 100644
--- a/harper-core/src/linting/compound_nouns/compound_noun_before_aux_verb.rs
+++ b/harper-core/src/linting/compound_nouns/compound_noun_before_aux_verb.rs
@@ -1,10 +1,10 @@
use crate::{
CharStringExt, Lrc, TokenStringExt,
linting::PatternLinter,
- patterns::{All, SplitCompoundWord},
+ patterns::{All, MergeableWords},
};
-use super::{Lint, LintKind, Suggestion, create_split_pattern, is_content_word};
+use super::{Lint, LintKind, Suggestion, is_content_word, predicate};
use crate::{
Token,
@@ -14,7 +14,7 @@ use crate::{
/// Two adjacent words separated by whitespace that if joined would be a valid noun.
pub struct CompoundNounBeforeAuxVerb {
pattern: Box<dyn Pattern>,
- split_pattern: Lrc<SplitCompoundWord>,
+ split_pattern: Lrc<MergeableWords>,
}
impl Default for CompoundNounBeforeAuxVerb {
@@ -25,7 +25,9 @@ impl Default for CompoundNounBeforeAuxVerb {
.then(is_content_word)
.then_auxiliary_verb();
- let split_pattern = create_split_pattern();
+ let split_pattern = Lrc::new(MergeableWords::new(|meta_closed, meta_open| {
+ predicate(meta_closed, meta_open)
+ }));
let mut pattern = All::default();
pattern.add(Box::new(context_pattern));
diff --git a/harper-core/src/linting/compound_nouns/mod.rs b/harper-core/src/linting/compound_nouns/mod.rs
index 10cc1dbf3..ce05e4fd7 100644
--- a/harper-core/src/linting/compound_nouns/mod.rs
+++ b/harper-core/src/linting/compound_nouns/mod.rs
@@ -3,7 +3,7 @@ mod compound_noun_after_possessive;
mod compound_noun_before_aux_verb;
use super::{Lint, LintKind, Suggestion, merge_linters::merge_linters};
-use crate::{Lrc, Token, patterns::SplitCompoundWord};
+use crate::{Token, WordMetadata};
// Helper function to check if a token is a content word (not a function word)
pub(crate) fn is_content_word(tok: &Token, src: &[char]) -> bool {
@@ -21,10 +21,8 @@ pub(crate) fn is_content_word(tok: &Token, src: &[char]) -> bool {
&& !meta.is_auxiliary_verb()
}
-pub(crate) fn create_split_pattern() -> Lrc<SplitCompoundWord> {
- Lrc::new(SplitCompoundWord::new(|meta| {
- meta.is_noun() && !meta.is_proper_noun()
- }))
+pub(crate) fn predicate(closed: Option<&WordMetadata>, open: Option<&WordMetadata>) -> bool {
+ open.is_none() && closed.is_some_and(|m| m.is_noun() && !m.is_proper_noun())
}
use compound_noun_after_det_adj::CompoundNounAfterDetAdj;
diff --git a/harper-core/src/patterns/mergeable_words.rs b/harper-core/src/patterns/mergeable_words.rs
new file mode 100644
index 000000000..344084d9b
--- /dev/null
+++ b/harper-core/src/patterns/mergeable_words.rs
@@ -0,0 +1,151 @@
+use std::sync::Arc;
+
+use crate::{CharString, Dictionary, FstDictionary, Token, WordMetadata};
+
+use super::{EitherPattern, Pattern, SequencePattern, WhitespacePattern};
+
+type PredicateFn = dyn Fn(Option<&WordMetadata>, Option<&WordMetadata>) -> bool + Send + Sync;
+
+/// A [`Pattern`] that identifies adjacent words that could potentially be merged into a single word.
+///
+/// This checks if two adjacent words could form a valid compound word, but first verifies
+/// that the two words aren't already a valid lexeme in the dictionary (like "straight away").
+pub struct MergeableWords {
+ inner: SequencePattern,
+ dict: Arc<FstDictionary>,
+ predicate: Box<PredicateFn>,
+}
+
+impl MergeableWords {
+ pub fn new(
+ predicate: impl Fn(Option<&WordMetadata>, Option<&WordMetadata>) -> bool + Send + Sync + 'static,
+ ) -> Self {
+ Self {
+ inner: SequencePattern::default()
+ .then_any_word()
+ .then(EitherPattern::new(vec![
+ Box::new(WhitespacePattern),
+ Box::new(|tok: &Token, _source: &[char]| tok.kind.is_hyphen()),
+ ]))
+ .then_any_word(),
+ dict: FstDictionary::curated(),
+ predicate: Box::new(predicate),
+ }
+ }
+
+ /// Get the merged word from the dictionary if these words can be merged.
+ /// Returns None if the words should remain separate (according to the predicate).
+ pub fn get_merged_word(
+ &self,
+ word_a: &Token,
+ word_b: &Token,
+ source: &[char],
+ ) -> Option<CharString> {
+ let a_chars: CharString = word_a.span.get_content(source).into();
+ let b_chars: CharString = word_b.span.get_content(source).into();
+
+ // First check if the open compound exists in the dictionary
+ let mut compound = a_chars.clone();
+ compound.push(' ');
+ compound.extend_from_slice(&b_chars);
+ let meta_open = self.dict.get_word_metadata(&compound);
+
+ // Then check if the closed compound exists in the dictionary
+ compound.remove(a_chars.len());
+ let meta_closed = self.dict.get_word_metadata(&compound);
+
+ if (self.predicate)(meta_closed, meta_open) {
+ return Some(compound);
+ }
+
+ None
+ }
+}
+
+impl Pattern for MergeableWords {
+ fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
+ let inner_match = self.inner.matches(tokens, source)?;
+
+ if inner_match != 3 {
+ return None;
+ }
+
+ if self
+ .get_merged_word(&tokens[0], &tokens[2], source)
+ .is_some()
+ {
+ return Some(inner_match);
+ }
+
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::{Document, WordMetadata, patterns::MergeableWords};
+
+ fn predicate(meta_closed: Option<&WordMetadata>, meta_open: Option<&WordMetadata>) -> bool {
+ meta_open.is_none() && meta_closed.map_or(false, |m| m.is_noun() && !m.is_proper_noun())
+ }
+
+ #[test]
+ fn merges_open_compound_not_in_dict() {
+ // note book is not in the dictionary, but notebook is
+ let doc = Document::new_plain_english_curated("note book");
+ let a = doc.tokens().nth(0).unwrap();
+ let b = doc.tokens().nth(2).unwrap();
+
+ let merged = MergeableWords::new(predicate).get_merged_word(&a, &b, doc.get_source());
+
+ assert_eq!(merged, Some("notebook".chars().collect()));
+ }
+
+ #[test]
+ fn does_not_merge_open_compound_in_dict() {
+ // straight away is not in the dictionary, but straightaway is
+ let doc = Document::new_plain_english_curated("straight away");
+ let a = doc.tokens().nth(0).unwrap();
+ let b = doc.tokens().nth(2).unwrap();
+
+ let merged = MergeableWords::new(predicate).get_merged_word(&a, &b, doc.get_source());
+
+ assert_eq!(merged, None);
+ }
+
+ #[test]
+ fn does_not_merge_invalid_compound() {
+ // neither quick for nor quickfox are in the dictionary
+ let doc = Document::new_plain_english_curated("quick fox");
+ let a = doc.tokens().nth(0).unwrap();
+ let b = doc.tokens().nth(2).unwrap();
+
+ let merged = MergeableWords::new(predicate).get_merged_word(&a, &b, doc.get_source());
+
+ assert_eq!(merged, None);
+ }
+
+ #[test]
+ fn merges_open_compound() {
+ // Dictionary has "frontline" but not "front line"
+ let doc = Document::new_plain_english_curated("front line");
+ let a = doc.tokens().nth(0).unwrap();
+ let b = doc.tokens().nth(2).unwrap();
+
+ let merged = MergeableWords::new(predicate).get_merged_word(&a, &b, doc.get_source());
+
+ assert_eq!(merged, Some("frontline".chars().collect()));
+ }
+
+ #[test]
+ fn merges_hyphenated_compound() {
+ // Doesn't check for "front-line" in the dictionary but matches it and "frontline" is in the dictionary
+ let doc = Document::new_plain_english_curated("front-line");
+ let a = doc.tokens().nth(0).unwrap();
+ let b = doc.tokens().nth(2).unwrap();
+
+ let merged = MergeableWords::new(predicate).get_merged_word(&a, &b, doc.get_source());
+
+ assert_eq!(merged, Some("frontline".chars().collect()));
+ }
+}
diff --git a/harper-core/src/patterns/mod.rs b/harper-core/src/patterns/mod.rs
index a5d12e413..17cdac810 100644
--- a/harper-core/src/patterns/mod.rs
+++ b/harper-core/src/patterns/mod.rs
@@ -15,6 +15,7 @@ mod implies_quantity;
mod indefinite_article;
mod inflection_of_be;
mod invert;
+mod mergeable_words;
mod naive_pattern_group;
mod nominal_phrase;
mod pattern_map;
@@ -22,7 +23,6 @@ mod repeating_pattern;
mod sequence_pattern;
mod similar_to_phrase;
mod spelled_number_pattern;
-mod split_compound_word;
mod whitespace_pattern;
mod within_edit_distance;
mod word;
@@ -38,6 +38,7 @@ pub use implies_quantity::ImpliesQuantity;
pub use indefinite_article::IndefiniteArticle;
pub use inflection_of_be::InflectionOfBe;
pub use invert::Invert;
+pub use mergeable_words::MergeableWords;
pub use naive_pattern_group::NaivePatternGroup;
pub use nominal_phrase::NominalPhrase;
pub use pattern_map::PatternMap;
@@ -45,7 +46,6 @@ pub use repeating_pattern::RepeatingPattern;
pub use sequence_pattern::SequencePattern;
pub use similar_to_phrase::SimilarToPhrase;
pub use spelled_number_pattern::SpelledNumberPattern;
-pub use split_compound_word::SplitCompoundWord;
pub use whitespace_pattern::WhitespacePattern;
pub use word::Word;
pub use word_pattern_group::WordPatternGroup;
diff --git a/harper-core/src/patterns/split_compound_word.rs b/harper-core/src/patterns/split_compound_word.rs
deleted file mode 100644
index 445c9896c..000000000
--- a/harper-core/src/patterns/split_compound_word.rs
+++ /dev/null
@@ -1,76 +0,0 @@
-use std::sync::Arc;
-
-use crate::{CharString, Dictionary, FstDictionary, Token, WordMetadata};
-
-use super::{Pattern, SequencePattern};
-
-/// A [`Pattern`] that looks for valid words accidentally split by whitespace.
-///
-/// Note that matches of this pattern are not guaranteed to be valid if merged.
-pub struct SplitCompoundWord {
- inner: SequencePattern,
- dict: Arc<FstDictionary>,
- predicate: Box<dyn Fn(&WordMetadata) -> bool + Send + Sync>,
-}
-
-impl SplitCompoundWord {
- /// Create a new instance of the linter which will only look for compound words that fit the
- /// provided predicate.
- pub fn new(predicate: impl Fn(&WordMetadata) -> bool + Send + Sync + 'static) -> Self {
- Self {
- inner: SequencePattern::default()
- .then_any_word()
- .then_whitespace()
- .then_any_word(),
- dict: FstDictionary::curated(),
- predicate: Box::new(predicate),
- }
- }
-
- /// Get the merged word from the dictionary that this pattern would match on if it was split.
- pub fn get_merged_word(
- &self,
- word_a: &Token,
- word_b: &Token,
- source: &[char],
- ) -> Option<CharString> {
- let a_chars: CharString = word_a.span.get_content(source).into();
- let b_chars: CharString = word_b.span.get_content(source).into();
-
- let mut buffer = CharString::new();
-
- buffer.clear();
- buffer.extend_from_slice(&a_chars);
- buffer.extend_from_slice(&b_chars);
-
- if let Some(metadata) = self.dict.get_word_metadata(&buffer) {
- if (self.predicate)(metadata) {
- let correct = self.dict.get_correct_capitalization_of(&buffer).unwrap();
- buffer.clear();
- buffer.extend_from_slice(correct);
- return Some(buffer);
- }
- }
-
- None
- }
-}
-
-impl Pattern for SplitCompoundWord {
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
- let inner_match = self.inner.matches(tokens, source)?;
-
- if inner_match != 3 {
- return None;
- }
-
- let a = &tokens[0];
- let b = &tokens[2];
-
- if self.get_merged_word(a, b, source).is_some() {
- return Some(inner_match);
- }
-
- None
- }
-}