Skip to content

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

feat: created linter to correct undotted initialisms

Elijah Potter5357cb3d0500
diff --git a/harper-core/src/linting/dot_initialisms.rs b/harper-core/src/linting/dot_initialisms.rs
new file mode 100644
index 000000000..a5c7c33d9
--- /dev/null
+++ b/harper-core/src/linting/dot_initialisms.rs
@@ -0,0 +1,69 @@
+use hashbrown::HashMap;
+
+use super::{Lint, LintKind, PatternLinter, Suggestion};
+use crate::patterns::{Pattern, SequencePattern, WordPatternGroup};
+use crate::{Token, TokenStringExt};
+
+pub struct DotInitialisms {
+ pattern: Box<dyn Pattern>,
+ corrections: HashMap<&'static str, &'static str>
+}
+
+impl Default for DotInitialisms {
+ fn default() -> Self {
+ let mut patterns = WordPatternGroup::default();
+
+ let mut corrections = HashMap::new();
+ corrections.insert("ie", "i.e.");
+ corrections.insert("eg", "e.g.");
+
+ for target in corrections.keys() {
+ let pattern = SequencePattern::default()
+ .then_exact_word(target)
+ .then_punctuation();
+
+ patterns.add(target, Box::new(pattern));
+ }
+
+ Self {
+ pattern: Box::new(patterns),
+ corrections
+ }
+ }
+}
+
+impl PatternLinter for DotInitialisms {
+ fn pattern(&self) -> &dyn Pattern {
+ self.pattern.as_ref()
+ }
+
+ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Lint {
+ let found_word_tok = matched_tokens.first().unwrap();
+ let found_word = found_word_tok.span.get_content_string(source);
+
+ let correction = self.corrections.get(found_word.as_str()).unwrap();
+
+ Lint {
+ span: matched_tokens.span().unwrap(),
+ lint_kind: LintKind::Formatting,
+ suggestions: vec![Suggestion::ReplaceWith(correction.chars().collect())],
+ message: "Initialisms should have dot-separated letters.".to_owned(),
+ priority: 63
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::DotInitialisms;
+ use crate::linting::tests::assert_suggestion_result;
+
+ #[test]
+ fn matches_eg() {
+ assert_suggestion_result(
+ "Some text here (eg. more text).",
+ DotInitialisms::default(),
+ "Some text here (e.g. more text)."
+ )
+ }
+}
diff --git a/harper-core/src/linting/lint.rs b/harper-core/src/linting/lint.rs
index 0434ed6a2..08b42bb12 100644
--- a/harper-core/src/linting/lint.rs
+++ b/harper-core/src/linting/lint.rs
@@ -60,6 +60,34 @@ pub enum Suggestion {
Remove
}
+impl Suggestion {
+ /// Apply a suggestion to a given text.
+ pub fn apply(&self, span: Span, source: &mut Vec<char>) {
+ match self {
+ Self::ReplaceWith(chars) => {
+ // Avoid allocation if possible
+ if chars.len() == span.len() {
+ for (index, c) in chars.iter().enumerate() {
+ source[index + span.start] = *c
+ }
+ } else {
+ let popped = source.split_off(span.start);
+
+ source.extend(chars);
+ source.extend(popped.into_iter().skip(span.len()));
+ }
+ }
+ Self::Remove => {
+ for i in span.end..source.len() {
+ source[i - span.len()] = source[i];
+ }
+
+ source.truncate(source.len() - span.len());
+ }
+ }
+ }
+}
+
impl Display for Suggestion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rs
index d15eab632..9e1f0a1c9 100644
--- a/harper-core/src/linting/lint_group.rs
+++ b/harper-core/src/linting/lint_group.rs
@@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize};
use super::an_a::AnA;
use super::avoid_curses::AvoidCurses;
use super::correct_number_suffix::CorrectNumberSuffix;
+use super::dot_initialisms::DotInitialisms;
use super::ellipsis_length::EllipsisLength;
use super::linking_verbs::LinkingVerbs;
use super::long_sentences::LongSentences;
@@ -113,7 +114,8 @@ create_lint_group_config!(
LinkingVerbs => false,
AvoidCurses => true,
TerminatingConjunctions => true,
- EllipsisLength => true
+ EllipsisLength => true,
+ DotInitialisms => true
);
impl<T: Dictionary + Default> Default for LintGroup<T> {
diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rs
index e68f931d8..49275f5f3 100644
--- a/harper-core/src/linting/mod.rs
+++ b/harper-core/src/linting/mod.rs
@@ -1,6 +1,7 @@
mod an_a;
mod avoid_curses;
mod correct_number_suffix;
+mod dot_initialisms;
mod ellipsis_length;
mod linking_verbs;
mod lint;
@@ -22,6 +23,7 @@ mod wrong_quotes;
pub use an_a::AnA;
pub use avoid_curses::AvoidCurses;
pub use correct_number_suffix::CorrectNumberSuffix;
+pub use dot_initialisms::DotInitialisms;
pub use ellipsis_length::EllipsisLength;
pub use linking_verbs::LinkingVerbs;
pub use lint::{Lint, LintKind, Suggestion};
@@ -62,4 +64,23 @@ mod tests {
dbg!(&lints);
assert_eq!(lints.len(), count);
}
+
+ /// Runs a provided linter on text, applies the first suggestion from each
+ /// lint and asserts that the result is equal to a given value.
+ pub fn assert_suggestion_result(text: &str, mut linter: impl Linter, expected_result: &str) {
+ let test = Document::new_markdown_curated(text);
+ let lints = linter.lint(&test);
+
+ let mut text: Vec<char> = text.chars().collect();
+
+ for lint in lints {
+ if let Some(sug) = lint.suggestions.first() {
+ sug.apply(lint.span, &mut text);
+ }
+ }
+
+ let transformed_str: String = text.iter().collect();
+
+ assert_eq!(transformed_str.as_str(), expected_result);
+ }
}
diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rs
index fa9859fed..e8b13b9b3 100644
--- a/harper-wasm/src/lib.rs
+++ b/harper-wasm/src/lib.rs
@@ -68,28 +68,7 @@ pub fn apply_suggestion(
let mut source: Vec<_> = text.chars().collect();
let span: harper_core::Span = span.into();
- match &suggestion.inner {
- harper_core::linting::Suggestion::ReplaceWith(chars) => {
- // Avoid allocation if possible
- if chars.len() == span.len() {
- for (index, c) in chars.iter().enumerate() {
- source[index + span.start] = *c
- }
- } else {
- let popped = source.split_off(span.start);
-
- source.extend(chars);
- source.extend(popped.into_iter().skip(span.len()));
- }
- }
- harper_core::linting::Suggestion::Remove => {
- for i in span.end..source.len() {
- source[i - span.len()] = source[i];
- }
-
- source.truncate(source.len() - span.len());
- }
- }
+ suggestion.inner.apply(span, &mut source);
Ok(source.iter().collect())
}