Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(core): Lint for those who don't like Oxford commas
hippietrail2733b59f3407
diff --git a/harper-core/src/document.rs b/harper-core/src/document.rsindex 7b5bf493a..fd9fe6a3d 100644--- a/harper-core/src/document.rs+++ b/harper-core/src/document.rs@@ -542,6 +542,7 @@ impl TokenStringExt for Document {create_fns_on_doc!(punctuation);create_fns_on_doc!(currency);create_fns_on_doc!(likely_homograph);+ create_fns_on_doc!(comma);fn first_sentence_word(&self) -> Option<Token> {self.tokens.first_sentence_word()diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rsindex 4f2563c67..3b1dcdadf 100644--- a/harper-core/src/linting/lint_group.rs+++ b/harper-core/src/linting/lint_group.rs@@ -33,7 +33,7 @@ use super::that_which::ThatWhich;use super::unclosed_quotes::UnclosedQuotes;use super::use_genitive::UseGenitive;use super::wrong_quotes::WrongQuotes;-use super::{CurrencyPlacement, Lint, Linter, OxfordComma};+use super::{CurrencyPlacement, Lint, Linter, NoOxfordComma, OxfordComma};use crate::{Dictionary, Document};macro_rules! create_lint_group_config {@@ -190,6 +190,7 @@ create_lint_group_config!(MergeWords => true,PluralConjugate => false,OxfordComma => true,+ NoOxfordComma => true,PronounContraction => true,CurrencyPlacement => true,SomewhatSomething => true,diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rsindex 48f26dd41..8d406eed1 100644--- a/harper-core/src/linting/mod.rs+++ b/harper-core/src/linting/mod.rs@@ -22,6 +22,7 @@ mod matcher;mod merge_linters;mod merge_words;mod multiple_sequential_pronouns;+mod no_oxford_comma;mod number_suffix_capitalization;mod oxford_comma;mod pattern_linter;@@ -59,6 +60,7 @@ pub use long_sentences::LongSentences;pub use matcher::Matcher;pub use merge_words::MergeWords;pub use multiple_sequential_pronouns::MultipleSequentialPronouns;+pub use no_oxford_comma::NoOxfordComma;pub use number_suffix_capitalization::NumberSuffixCapitalization;pub use oxford_comma::OxfordComma;pub use pattern_linter::PatternLinter;diff --git a/harper-core/src/linting/no_oxford_comma.rs b/harper-core/src/linting/no_oxford_comma.rsnew file mode 100644index 000000000..cf1b08095--- /dev/null+++ b/harper-core/src/linting/no_oxford_comma.rs@@ -0,0 +1,162 @@+use crate::{+ patterns::{Pattern, SequencePattern, WordSet},+ Document, Token, TokenStringExt,+};++use super::{Lint, LintKind, Linter, Suggestion};++pub struct NoOxfordComma {+ pattern: SequencePattern,+}++impl NoOxfordComma {+ pub fn new() -> Self {+ Self {+ pattern: SequencePattern::default()+ .then_noun_phrase()+ .then_comma()+ .then_whitespace()+ .then_noun_phrase()+ .then_comma()+ .then_whitespace()+ .then(Box::new(WordSet::all(&["and", "or", "nor"]))),+ }+ }++ fn match_to_lint(&self, matched_toks: &[Token], _source: &[char]) -> Lint {+ let last_comma_index = matched_toks.last_comma_index().unwrap();+ let offender = matched_toks[last_comma_index];++ Lint {+ span: offender.span,+ lint_kind: LintKind::Style,+ suggestions: vec![Suggestion::Remove],+ message: "Remove the Oxford comma here.".to_owned(),+ priority: 31,+ }+ }+}++impl Default for NoOxfordComma {+ fn default() -> Self {+ Self::new()+ }+}++impl Linter for NoOxfordComma {+ 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. Enabling this lint checks that there is no comma before `and`, `or` or `nor` when listing out more than two ideas."+ }+}++#[cfg(test)]+mod tests {+ use crate::linting::tests::{assert_lint_count, assert_suggestion_result};++ use super::NoOxfordComma;++ #[test]+ fn fruits() {+ assert_lint_count(+ "An apple, a banana, and a pear",+ NoOxfordComma::default(),+ 1,+ );+ }++ #[test]+ fn people() {+ assert_suggestion_result(+ "Nancy, Steve, and Carl are going to the coffee shop.",+ NoOxfordComma::default(),+ "Nancy, Steve and Carl are going to the coffee shop.",+ );+ }++ #[test]+ fn places() {+ assert_suggestion_result(+ "I've always wanted to visit Paris, Tokyo, and Rome.",+ NoOxfordComma::default(),+ "I've always wanted to visit Paris, Tokyo and Rome.",+ );+ }++ #[test]+ fn foods() {+ assert_suggestion_result(+ "My favorite foods are pizza, sushi, tacos, and burgers.",+ NoOxfordComma::default(),+ "My favorite foods are pizza, sushi, tacos and burgers.",+ );+ }++ #[test]+ fn allows_clean_music() {+ assert_lint_count(+ "I enjoy listening to pop music, rock, hip-hop, electronic dance and classical music.",+ NoOxfordComma::default(),+ 0,+ );+ }++ #[test]+ fn allows_clean_nations() {+ assert_lint_count("The team consists of players from different countries: France, Germany, Italy and Spain.", NoOxfordComma::default(), 0);+ }++ #[test]+ fn or_writing() {+ assert_suggestion_result("Harper can be a lifesaver when writing technical documents, emails, or other formal forms of communication.", NoOxfordComma::default(), "Harper can be a lifesaver when writing technical documents, emails or other formal forms of communication.",);+ }++ #[test]+ fn sports() {+ assert_suggestion_result(+ "They enjoy playing soccer, basketball, or tennis.",+ NoOxfordComma::default(),+ "They enjoy playing soccer, basketball or tennis.",+ );+ }++ #[test]+ fn nor_vegetables() {+ assert_suggestion_result(+ "I like carrots, kale, nor broccoli.",+ NoOxfordComma::default(),+ "I like carrots, kale nor broccoli.",+ );+ }+}diff --git a/harper-core/src/token.rs b/harper-core/src/token.rsindex 83eb246f1..af8892a01 100644--- a/harper-core/src/token.rs+++ b/harper-core/src/token.rs@@ -96,6 +96,7 @@ pub trait TokenStringExt {create_decl_for!(punctuation);create_decl_for!(currency);create_decl_for!(likely_homograph);+ create_decl_for!(comma);fn iter_linking_verb_indices(&self) -> impl Iterator<Item = usize> + '_;fn iter_linking_verbs(&self) -> impl Iterator<Item = Token> + '_;@@ -137,6 +138,7 @@ impl TokenStringExt for [Token] {create_fns_for!(chunk_terminator);create_fns_for!(currency);create_fns_for!(likely_homograph);+ create_fns_for!(comma);fn first_non_whitespace(&self) -> Option<Token> {self.iter().find(|t| !t.kind.is_whitespace()).copied()