Skip to content

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

feat: wrote linter for Oxford commas

Elijah Potter180e3aff1a9f
diff --git a/harper-core/dictionary.dict b/harper-core/dictionary.dict
index 6c8d07a80..ead6ece24 100644
--- a/harper-core/dictionary.dict
+++ b/harper-core/dictionary.dict
@@ -1,5 +1,4 @@
50000
-A/125SM
AA/1254M
AAA/12
AB/215M
@@ -10758,7 +10757,7 @@ Zworykin/M
Zyrtec/M
Zyuganov/M
Zzz
-a/1-+4857S~
+a/-+457S~
aah/14
aardvark/1SM
ab/14+SDY
@@ -11894,7 +11893,7 @@ amusing/45Y
amygdala/1
amylase/1M
amyloid/15
-an/-71+CS~
+an/-7+CS~
anabolism/1M
anachronism/1SM
anachronistic/5
@@ -11955,7 +11954,7 @@ anchovy/1SM
ancient/51SPMRYT
ancientness/1M
ancillary/51SM
-and/714~
+and/74~
andante/15SM
andiron/1SM
androgen/1M
@@ -13329,7 +13328,7 @@ bamboozle/41DSG
ban/41SM
banal/5Y
banality/1SM
-banana/15SM
+banana/1SM
band's
band/14ESGD
bandage/14DSMG
diff --git a/harper-core/src/document.rs b/harper-core/src/document.rs
index 61b75f4d0..e1378485e 100644
--- a/harper-core/src/document.rs
+++ b/harper-core/src/document.rs
@@ -490,6 +490,7 @@ macro_rules! create_fns_on_doc {
impl TokenStringExt for Document {
create_fns_on_doc!(word);
+ create_fns_on_doc!(conjunction);
create_fns_on_doc!(space);
create_fns_on_doc!(apostrophe);
create_fns_on_doc!(pipe);
diff --git a/harper-core/src/linting/lint.rs b/harper-core/src/linting/lint.rs
index 6c92706f3..532a3604d 100644
--- a/harper-core/src/linting/lint.rs
+++ b/harper-core/src/linting/lint.rs
@@ -32,6 +32,7 @@ impl Default for Lint {
pub enum LintKind {
Spelling,
Capitalization,
+ Style,
Formatting,
Repetition,
Enhancement,
@@ -52,6 +53,7 @@ impl Display for LintKind {
LintKind::Miscellaneous => "Miscellaneous",
LintKind::Enhancement => "Enhancement",
LintKind::WordChoice => "Word Choice",
+ LintKind::Style => "Style",
};
write!(f, "{}", s)
@@ -61,6 +63,8 @@ impl Display for LintKind {
#[derive(Debug, Clone, Serialize, Deserialize, Is)]
pub enum Suggestion {
ReplaceWith(Vec<char>),
+ /// Insert the provided characters _after_ the offending text.
+ InsertAfter(Vec<char>),
Remove,
}
@@ -88,6 +92,11 @@ impl Suggestion {
source.truncate(source.len() - span.len());
}
+ Self::InsertAfter(chars) => {
+ let popped = source.split_off(span.end);
+ source.extend(chars);
+ source.extend(popped);
+ }
}
}
}
@@ -98,7 +107,27 @@ impl Display for Suggestion {
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<_>>());
+ }
+}
diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rs
index b6b4aa93d..b39ff81b8 100644
--- a/harper-core/src/linting/lint_group.rs
+++ b/harper-core/src/linting/lint_group.rs
@@ -29,7 +29,7 @@ use super::that_which::ThatWhich;
use super::unclosed_quotes::UnclosedQuotes;
use super::use_genitive::UseGenitive;
use super::wrong_quotes::WrongQuotes;
-use super::{Lint, Linter};
+use super::{Lint, Linter, OxfordComma};
use crate::{Dictionary, Document};
macro_rules! create_lint_group_config {
@@ -183,7 +183,8 @@ create_lint_group_config!(
AppleNames => true,
AzureNames => true,
MergeWords => true,
- PluralConjugate => false
+ PluralConjugate => false,
+ OxfordComma => 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 deec6fa13..8f64ff574 100644
--- a/harper-core/src/linting/mod.rs
+++ b/harper-core/src/linting/mod.rs
@@ -14,6 +14,7 @@ mod matcher;
mod merge_words;
mod multiple_sequential_pronouns;
mod number_suffix_capitalization;
+mod oxford_comma;
mod pattern_linter;
mod plural_conjugate;
mod proper_noun_capitalization_linters;
@@ -43,6 +44,7 @@ pub use matcher::Matcher;
pub use merge_words::MergeWords;
pub use multiple_sequential_pronouns::MultipleSequentialPronouns;
pub use number_suffix_capitalization::NumberSuffixCapitalization;
+pub use oxford_comma::OxfordComma;
pub use pattern_linter::PatternLinter;
pub use proper_noun_capitalization_linters::{
AmazonNames, Americas, AppleNames, AzureNames, ChineseCommunistParty, GoogleNames, Holidays,
@@ -97,7 +99,7 @@ mod tests {
}
/// Runs a provided linter on text, applies the first suggestion from each
- /// lint and asserts that the result is equal to a given value.
+ /// lint and asserts whether 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);
@@ -105,6 +107,7 @@ mod tests {
let mut text: Vec<char> = text.chars().collect();
for lint in lints {
+ dbg!(&lint);
if let Some(sug) = lint.suggestions.first() {
sug.apply(lint.span, &mut text);
}
diff --git a/harper-core/src/linting/oxford_comma.rs b/harper-core/src/linting/oxford_comma.rs
new file mode 100644
index 000000000..01fcc2d82
--- /dev/null
+++ b/harper-core/src/linting/oxford_comma.rs
@@ -0,0 +1,108 @@
+use crate::{
+ patterns::{Pattern, SequencePattern},
+ Document, Token, TokenStringExt,
+};
+
+use super::{Lint, LintKind, Linter, Suggestion};
+
+pub struct OxfordComma {
+ pattern: SequencePattern,
+}
+
+impl OxfordComma {
+ pub fn new() -> Self {
+ Self {
+ pattern: SequencePattern::default()
+ .then_one_or_more(Box::new(
+ SequencePattern::default()
+ .then_noun_phrase()
+ .then_comma()
+ .then_whitespace(),
+ ))
+ .then_noun_phrase()
+ .then_whitespace()
+ .then_exact_word("and")
+ .then_whitespace()
+ .then_noun_phrase(),
+ }
+ }
+
+ fn match_to_lint(&self, matched_toks: &[Token], _source: &[char]) -> Lint {
+ let conj_index = matched_toks.last_conjunction_index().unwrap();
+ let offender = matched_toks[conj_index - 2];
+
+ Lint {
+ span: offender.span,
+ lint_kind: LintKind::Style,
+ suggestions: vec![Suggestion::InsertAfter(vec![','])],
+ message: "An Oxford comma is necessary here.".to_owned(),
+ priority: 31,
+ }
+ }
+}
+
+impl Default for OxfordComma {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Linter for OxfordComma {
+ fn lint(&mut self, document: &Document) -> Vec<Lint> {
+ let mut lints = Vec::new();
+
+ for sentence in document.iter_sentences() {
+ let mut tok_cursor = 0;
+
+ loop {
+ if tok_cursor >= sentence.len() {
+ break;
+ }
+
+ let match_len = self
+ .pattern
+ .matches(&sentence[tok_cursor..], document.get_source());
+
+ if match_len != 0 {
+ let lint = self.match_to_lint(
+ &sentence[tok_cursor..tok_cursor + match_len],
+ document.get_source(),
+ );
+
+ lints.push(lint);
+ tok_cursor += match_len;
+ } else {
+ tok_cursor += 1;
+ }
+ }
+ }
+
+ lints
+ }
+
+ fn description(&self) -> &str {
+ "The Oxford comma is one of the more controversial rules in common use today. Here, we make sure that we put a comma before `and` when listing out more than two ideas."
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::linting::tests::{assert_lint_count, assert_suggestion_result};
+
+ use super::OxfordComma;
+
+ #[test]
+ fn fruits() {
+ assert_lint_count("An apple, a banana and a pear", OxfordComma::default(), 1);
+ }
+
+ #[test]
+ fn people() {
+ // Nancy, Steve and Carl are going
+ assert_suggestion_result(
+ "Nancy, Steve and Carl are going to the coffee shop.",
+ OxfordComma::default(),
+ "Nancy, Steve, and Carl are going to the coffee shop.",
+ );
+ }
+}
diff --git a/harper-core/src/patterns/mod.rs b/harper-core/src/patterns/mod.rs
index 39fd588b7..ae50e2156 100644
--- a/harper-core/src/patterns/mod.rs
+++ b/harper-core/src/patterns/mod.rs
@@ -1,6 +1,6 @@
use std::collections::VecDeque;
-use crate::{document, Document, Span, Token, VecExt};
+use crate::{Document, Span, Token, VecExt};
mod any_pattern;
mod consumes_remaining_pattern;
@@ -8,6 +8,7 @@ mod either_pattern;
mod invert;
mod is_not_title_case;
mod naive_pattern_group;
+mod noun_phrase;
mod repeating_pattern;
mod sequence_pattern;
mod token_kind_pattern_group;
@@ -21,6 +22,7 @@ pub use either_pattern::EitherPattern;
pub use invert::Invert;
pub use is_not_title_case::IsNotTitleCase;
pub use naive_pattern_group::NaivePatternGroup;
+pub use noun_phrase::NounPhrase;
pub use repeating_pattern::RepeatingPattern;
pub use sequence_pattern::SequencePattern;
pub use token_kind_pattern_group::TokenKindPatternGroup;
diff --git a/harper-core/src/patterns/noun_phrase.rs b/harper-core/src/patterns/noun_phrase.rs
new file mode 100644
index 000000000..31d18bc04
--- /dev/null
+++ b/harper-core/src/patterns/noun_phrase.rs
@@ -0,0 +1,78 @@
+use crate::Token;
+
+use super::Pattern;
+
+/// A pattern that returns the value of the first non-zero match in a list.
+#[derive(Default)]
+pub struct NounPhrase;
+
+impl Pattern for NounPhrase {
+ fn matches(&self, tokens: &[Token], _source: &[char]) -> usize {
+ let mut cursor = 0;
+
+ loop {
+ let Some(tok) = tokens.get(cursor) else {
+ return 0;
+ };
+
+ if tok.kind.is_adjective() || tok.kind.is_article() {
+ let Some(next) = tokens.get(cursor + 1) else {
+ return 0;
+ };
+
+ if !next.kind.is_whitespace() {
+ return 0;
+ }
+
+ cursor += 2;
+ continue;
+ }
+
+ if tok.kind.is_noun() {
+ return cursor + 1;
+ }
+
+ return 0;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::DocPattern;
+ use super::NounPhrase;
+ use crate::{patterns::Pattern, Document, Span};
+
+ #[test]
+ fn simple_apple() {
+ let doc = Document::new_markdown_curated("A red apple");
+ let matches = NounPhrase.find_all_matches_in_doc(&doc);
+
+ assert_eq!(matches, vec![Span::new(0, 5)])
+ }
+
+ #[test]
+ fn complex_apple() {
+ let doc = Document::new_markdown_curated("A red apple with a long stem");
+ let matches = NounPhrase.find_all_matches_in_doc(&doc);
+
+ assert_eq!(matches, vec![Span::new(0, 5), Span::new(8, 13)])
+ }
+
+ #[test]
+ fn list_fruit() {
+ let doc = Document::new_markdown_curated("An apple, a banana and a pear");
+ let matches = NounPhrase.find_all_matches_in_doc(&doc);
+
+ assert_eq!(
+ matches,
+ vec![Span::new(0, 3), Span::new(5, 8), Span::new(11, 14)]
+ )
+ }
+
+ #[test]
+ fn simplest_banana() {
+ let doc = Document::new_markdown_curated("a banana");
+ assert!(NounPhrase.matches(doc.get_tokens(), doc.get_source()) != 0);
+ }
+}
diff --git a/harper-core/src/patterns/sequence_pattern.rs b/harper-core/src/patterns/sequence_pattern.rs
index 8a75a186e..1d4d63218 100644
--- a/harper-core/src/patterns/sequence_pattern.rs
+++ b/harper-core/src/patterns/sequence_pattern.rs
@@ -2,7 +2,7 @@ use hashbrown::HashSet;
use paste::paste;
use super::whitespace_pattern::WhitespacePattern;
-use super::{EitherPattern, Pattern, RepeatingPattern};
+use super::{NounPhrase, Pattern, RepeatingPattern};
use crate::{CharStringExt, Lrc, Token, TokenKind};
/// A pattern that checks that a sequence of other patterns match.
@@ -59,19 +59,8 @@ impl SequencePattern {
gen_then_from_is!(hyphen);
/// Add a pattern that looks for more complex ideas, like nouns with adjectives attached.
- pub fn then_idea(mut self) -> Self {
- self.then(Box::new(EitherPattern::new(vec![
- Box::new(
- SequencePattern::default()
- .then_one_or_more(Box::new(
- SequencePattern::default()
- .then_adjective()
- .then_whitespace(),
- ))
- .then_noun(),
- ),
- Box::new(SequencePattern::default().then_noun()),
- ])))
+ pub fn then_noun_phrase(self) -> Self {
+ self.then(Box::new(NounPhrase))
}
pub fn then_exact_word(mut self, word: &'static str) -> Self {
@@ -236,8 +225,8 @@ mod tests {
use hashbrown::HashSet;
use super::SequencePattern;
- use crate::patterns::{DocPattern, Pattern};
- use crate::{Document, Lrc, Span};
+ use crate::patterns::Pattern;
+ use crate::{Document, Lrc};
#[test]
fn matches_n_whitespace_tokens() {
@@ -287,24 +276,4 @@ mod tests {
doc.get_tokens().len()
);
}
-
- #[test]
- fn simple_idea_apple() {
- let doc = Document::new_markdown_curated("A red apple");
- let matches = SequencePattern::default()
- .then_idea()
- .find_all_matches_in_doc(&doc);
-
- assert_eq!(matches, vec![Span::new(0, 5)])
- }
-
- #[test]
- fn complex_idea_apple() {
- let doc = Document::new_markdown_curated("A red apple with a long stem");
- let matches = SequencePattern::default()
- .then_idea()
- .find_all_matches_in_doc(&doc);
-
- assert_eq!(matches, vec![Span::new(0, 5), Span::new(8, 13)])
- }
}
diff --git a/harper-core/src/token.rs b/harper-core/src/token.rs
index 5eaa36c79..4435173c8 100644
--- a/harper-core/src/token.rs
+++ b/harper-core/src/token.rs
@@ -79,6 +79,7 @@ pub trait TokenStringExt {
fn span(&self) -> Option<Span>;
create_decl_for!(word);
+ create_decl_for!(conjunction);
create_decl_for!(space);
create_decl_for!(apostrophe);
create_decl_for!(pipe);
@@ -117,6 +118,7 @@ pub trait TokenStringExt {
impl TokenStringExt for [Token] {
create_fns_for!(word);
+ create_fns_for!(conjunction);
create_fns_for!(space);
create_fns_for!(apostrophe);
create_fns_for!(pipe);
diff --git a/harper-core/src/token_kind.rs b/harper-core/src/token_kind.rs
index b669c0404..015d82db1 100644
--- a/harper-core/src/token_kind.rs
+++ b/harper-core/src/token_kind.rs
@@ -91,6 +91,10 @@ impl TokenKind {
}
}
+ pub fn is_article(&self) -> bool {
+ matches!(self, TokenKind::Word(WordMetadata { article: true, .. }))
+ }
+
pub fn is_ellipsis(&self) -> bool {
matches!(self, TokenKind::Punctuation(Punctuation::Ellipsis))
}
diff --git a/harper-ls/src/diagnostics.rs b/harper-ls/src/diagnostics.rs
index 01348e4ce..e30710d40 100644
--- a/harper-ls/src/diagnostics.rs
+++ b/harper-ls/src/diagnostics.rs
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use harper_core::linting::{Lint, Suggestion};
+use harper_core::CharStringExt;
use tower_lsp::lsp_types::{
CodeAction, CodeActionKind, CodeActionOrCommand, Command, Diagnostic, TextEdit, Url,
WorkspaceEdit,
@@ -37,6 +38,11 @@ pub fn lint_to_code_actions<'a>(
let replace_string = match suggestion {
Suggestion::ReplaceWith(with) => with.iter().collect(),
Suggestion::Remove => "".to_string(),
+ Suggestion::InsertAfter(with) => format!(
+ "{}{}",
+ lint.span.get_content_string(source),
+ with.to_string()
+ ),
};
Some(CodeAction {
diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rs
index cb3c466f4..7343462ee 100644
--- a/harper-wasm/src/lib.rs
+++ b/harper-wasm/src/lib.rs
@@ -166,6 +166,7 @@ pub struct Suggestion {
pub enum SuggestionKind {
Replace = 0,
Remove = 1,
+ InsertAfter = 2,
}
#[wasm_bindgen]
@@ -174,13 +175,14 @@ impl Suggestion {
Self { inner }
}
- /// Get the text that is going to replace error.
+ /// Get the text that is going to replace the problematic section.
/// If [`Self::kind`] is `SuggestionKind::Remove`, this will return an empty
/// string.
pub fn get_replacement_text(&self) -> String {
match &self.inner {
harper_core::linting::Suggestion::Remove => "".to_string(),
harper_core::linting::Suggestion::ReplaceWith(chars) => chars.iter().collect(),
+ harper_core::linting::Suggestion::InsertAfter(chars) => chars.iter().collect(),
}
}
@@ -188,6 +190,7 @@ impl Suggestion {
match &self.inner {
harper_core::linting::Suggestion::Remove => SuggestionKind::Remove,
harper_core::linting::Suggestion::ReplaceWith(_) => SuggestionKind::Replace,
+ harper_core::linting::Suggestion::InsertAfter(_) => SuggestionKind::InsertAfter,
}
}
}