Skip to content

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

refactor(core): separated types into their own modules

Elijah Pottere55af52d9caf
diff --git a/harper-core/src/linting/lint.rs b/harper-core/src/linting/lint.rs
index add20daa0..960c5439c 100644
--- a/harper-core/src/linting/lint.rs
+++ b/harper-core/src/linting/lint.rs
@@ -1,10 +1,9 @@
-use std::fmt::Display;
-
-use is_macro::Is;
use serde::{Deserialize, Serialize};
use crate::Span;
+use super::{LintKind, Suggestion};
+
/// An error found in text.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Lint {
@@ -37,150 +36,3 @@ impl Default for Lint {
}
}
}
-
-/// The general category a [`Lint`] falls into.
-/// There's no reason not to add a new item here if you are adding a new rule that doesn't fit
-/// the existing categories.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, Is, Default)]
-pub enum LintKind {
- Spelling,
- Capitalization,
- Style,
- Formatting,
- Repetition,
- Enhancement,
- Readability,
- WordChoice,
- #[default]
- Miscellaneous,
-}
-
-impl Display for LintKind {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let s = match self {
- LintKind::Spelling => "Spelling",
- LintKind::Capitalization => "Capitalization",
- LintKind::Formatting => "Formatting",
- LintKind::Repetition => "Repetition",
- LintKind::Readability => "Readability",
- LintKind::Miscellaneous => "Miscellaneous",
- LintKind::Enhancement => "Enhancement",
- LintKind::WordChoice => "Word Choice",
- LintKind::Style => "Style",
- };
-
- write!(f, "{}", s)
- }
-}
-
-/// A suggested edit that could resolve a [`Lint`].
-#[derive(Debug, Clone, Serialize, Deserialize, Is, PartialEq, Eq)]
-pub enum Suggestion {
- /// Replace the offending text with a specific character sequence.
- ReplaceWith(Vec<char>),
- /// Insert the provided characters _after_ the offending text.
- InsertAfter(Vec<char>),
- /// Remove the offending text.
- Remove,
-}
-
-impl Suggestion {
- /// Variant of [`Self::replace_with_match_case`] that accepts a static string.
- pub fn replace_with_match_case_str(value: &'static str, template: &[char]) -> Self {
- Self::replace_with_match_case(value.chars().collect(), template)
- }
-
- /// Construct an instance of [`Self::ReplaceWith`], but make the content match the case of the
- /// provided template.
- ///
- /// For example, if we want to replace "You're" with "You are", we can provide "you are" and
- /// "You're".
- pub fn replace_with_match_case(mut value: Vec<char>, template: &[char]) -> Self {
- for (v, t) in value.iter_mut().zip(template.iter()) {
- if v.is_ascii_uppercase() != t.is_ascii_uppercase() {
- if t.is_uppercase() {
- *v = v.to_ascii_uppercase();
- } else {
- *v = v.to_ascii_lowercase();
- }
- }
- }
-
- Self::ReplaceWith(value)
- }
-
- /// 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());
- }
- Self::InsertAfter(chars) => {
- let popped = source.split_off(span.end);
- source.extend(chars);
- source.extend(popped);
- }
- }
- }
-}
-
-impl Display for Suggestion {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Suggestion::ReplaceWith(with) => {
- write!(f, "Replace with: “{}”", with.iter().collect::<String>())
- }
- Suggestion::InsertAfter(with) => {
- write!(f, "Insert “{}”", with.iter().collect::<String>())
- }
- Suggestion::Remove => write!(f, "Remove error"),
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use crate::Span;
-
- use super::Suggestion;
-
- #[test]
- fn insert_comma_after() {
- let source = "This is a test";
- let mut source_chars = source.chars().collect();
- let sug = Suggestion::InsertAfter(vec![',']);
- sug.apply(Span::new(0, 4), &mut source_chars);
-
- assert_eq!(source_chars, "This, is a test".chars().collect::<Vec<_>>());
- }
-
- #[test]
- fn suggestion_your_match_case() {
- let template: Vec<_> = "You're".chars().collect();
- let value: Vec<_> = "you are".chars().collect();
-
- let correct = "You are".chars().collect();
-
- assert_eq!(
- Suggestion::replace_with_match_case(value, &template),
- Suggestion::ReplaceWith(correct)
- )
- }
-}
diff --git a/harper-core/src/linting/lint_kind.rs b/harper-core/src/linting/lint_kind.rs
new file mode 100644
index 000000000..3357bf45b
--- /dev/null
+++ b/harper-core/src/linting/lint_kind.rs
@@ -0,0 +1,39 @@
+use std::fmt::Display;
+
+use is_macro::Is;
+use serde::{Deserialize, Serialize};
+
+/// The general category a [`Lint`] falls into.
+/// There's no reason not to add a new item here if you are adding a new rule that doesn't fit
+/// the existing categories.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Is, Default)]
+pub enum LintKind {
+ Spelling,
+ Capitalization,
+ Style,
+ Formatting,
+ Repetition,
+ Enhancement,
+ Readability,
+ WordChoice,
+ #[default]
+ Miscellaneous,
+}
+
+impl Display for LintKind {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let s = match self {
+ LintKind::Spelling => "Spelling",
+ LintKind::Capitalization => "Capitalization",
+ LintKind::Formatting => "Formatting",
+ LintKind::Repetition => "Repetition",
+ LintKind::Readability => "Readability",
+ LintKind::Miscellaneous => "Miscellaneous",
+ LintKind::Enhancement => "Enhancement",
+ LintKind::WordChoice => "Word Choice",
+ LintKind::Style => "Style",
+ };
+
+ write!(f, "{}", s)
+ }
+}
diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rs
index c21e3330c..606041390 100644
--- a/harper-core/src/linting/mod.rs
+++ b/harper-core/src/linting/mod.rs
@@ -15,6 +15,7 @@ mod lets_confusion;
mod linking_verbs;
mod lint;
mod lint_group;
+mod lint_kind;
mod long_sentences;
mod matcher;
mod merge_linters;
@@ -32,6 +33,7 @@ mod somewhat_something;
mod spaces;
mod spell_check;
mod spelled_numbers;
+mod suggestion;
mod terminating_conjunctions;
mod that_which;
mod unclosed_quotes;
@@ -48,8 +50,9 @@ pub use dot_initialisms::DotInitialisms;
pub use ellipsis_length::EllipsisLength;
pub use lets_confusion::LetsConfusion;
pub use linking_verbs::LinkingVerbs;
-pub use lint::{Lint, LintKind, Suggestion};
+pub use lint::Lint;
pub use lint_group::{LintGroup, LintGroupConfig};
+pub use lint_kind::LintKind;
pub use long_sentences::LongSentences;
pub use matcher::Matcher;
pub use merge_words::MergeWords;
@@ -69,6 +72,7 @@ pub use somewhat_something::SomewhatSomething;
pub use spaces::Spaces;
pub use spell_check::SpellCheck;
pub use spelled_numbers::SpelledNumbers;
+pub use suggestion::Suggestion;
pub use terminating_conjunctions::TerminatingConjunctions;
pub use that_which::ThatWhich;
pub use unclosed_quotes::UnclosedQuotes;
diff --git a/harper-core/src/linting/sentence_capitalization.rs b/harper-core/src/linting/sentence_capitalization.rs
index 449cb331e..7f4414828 100644
--- a/harper-core/src/linting/sentence_capitalization.rs
+++ b/harper-core/src/linting/sentence_capitalization.rs
@@ -1,6 +1,6 @@
use itertools::Itertools;
-use super::lint::Suggestion;
+use super::Suggestion;
use super::{Lint, LintKind, Linter};
use crate::document::Document;
use crate::{Token, TokenKind, TokenStringExt};
diff --git a/harper-core/src/linting/spell_check.rs b/harper-core/src/linting/spell_check.rs
index 60c16d581..1a9e2e082 100644
--- a/harper-core/src/linting/spell_check.rs
+++ b/harper-core/src/linting/spell_check.rs
@@ -1,7 +1,7 @@
use hashbrown::HashMap;
use smallvec::ToSmallVec;
-use super::lint::Suggestion;
+use super::Suggestion;
use super::{Lint, LintKind, Linter};
use crate::document::Document;
use crate::spell::suggest_correct_spelling;
diff --git a/harper-core/src/linting/suggestion.rs b/harper-core/src/linting/suggestion.rs
new file mode 100644
index 000000000..40fb5fb51
--- /dev/null
+++ b/harper-core/src/linting/suggestion.rs
@@ -0,0 +1,118 @@
+use std::fmt::Display;
+
+use is_macro::Is;
+use serde::{Deserialize, Serialize};
+
+use crate::Span;
+
+/// A suggested edit that could resolve a [`Lint`].
+#[derive(Debug, Clone, Serialize, Deserialize, Is, PartialEq, Eq)]
+pub enum Suggestion {
+ /// Replace the offending text with a specific character sequence.
+ ReplaceWith(Vec<char>),
+ /// Insert the provided characters _after_ the offending text.
+ InsertAfter(Vec<char>),
+ /// Remove the offending text.
+ Remove,
+}
+
+impl Suggestion {
+ /// Variant of [`Self::replace_with_match_case`] that accepts a static string.
+ pub fn replace_with_match_case_str(value: &'static str, template: &[char]) -> Self {
+ Self::replace_with_match_case(value.chars().collect(), template)
+ }
+
+ /// Construct an instance of [`Self::ReplaceWith`], but make the content match the case of the
+ /// provided template.
+ ///
+ /// For example, if we want to replace "You're" with "You are", we can provide "you are" and
+ /// "You're".
+ pub fn replace_with_match_case(mut value: Vec<char>, template: &[char]) -> Self {
+ for (v, t) in value.iter_mut().zip(template.iter()) {
+ if v.is_ascii_uppercase() != t.is_ascii_uppercase() {
+ if t.is_uppercase() {
+ *v = v.to_ascii_uppercase();
+ } else {
+ *v = v.to_ascii_lowercase();
+ }
+ }
+ }
+
+ Self::ReplaceWith(value)
+ }
+
+ /// 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());
+ }
+ Self::InsertAfter(chars) => {
+ let popped = source.split_off(span.end);
+ source.extend(chars);
+ source.extend(popped);
+ }
+ }
+ }
+}
+
+impl Display for Suggestion {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Suggestion::ReplaceWith(with) => {
+ write!(f, "Replace with: “{}”", with.iter().collect::<String>())
+ }
+ Suggestion::InsertAfter(with) => {
+ write!(f, "Insert “{}”", with.iter().collect::<String>())
+ }
+ Suggestion::Remove => write!(f, "Remove error"),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::Span;
+
+ use super::Suggestion;
+
+ #[test]
+ fn insert_comma_after() {
+ let source = "This is a test";
+ let mut source_chars = source.chars().collect();
+ let sug = Suggestion::InsertAfter(vec![',']);
+ sug.apply(Span::new(0, 4), &mut source_chars);
+
+ assert_eq!(source_chars, "This, is a test".chars().collect::<Vec<_>>());
+ }
+
+ #[test]
+ fn suggestion_your_match_case() {
+ let template: Vec<_> = "You're".chars().collect();
+ let value: Vec<_> = "you are".chars().collect();
+
+ let correct = "You are".chars().collect();
+
+ assert_eq!(
+ Suggestion::replace_with_match_case(value, &template),
+ Suggestion::ReplaceWith(correct)
+ )
+ }
+}