Skip to content

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

refactor(core): use only one `Linter` type for `phrase_corrections`

Elijah Pottere26908dfec1e
diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rs
index f392cecba..b78199b53 100644
--- a/harper-cli/src/main.rs
+++ b/harper-cli/src/main.rs
@@ -64,7 +64,7 @@ fn main() -> anyhow::Result<()> {
Args::Lint { file, count } => {
let (doc, source) = load_file(&file, markdown_options)?;
- let mut linter = LintGroup::new(linting_options, dictionary);
+ let mut linter = LintGroup::new_curated(linting_options, dictionary);
let mut lints = linter.lint(&doc);
if count {
@@ -199,8 +199,8 @@ fn main() -> anyhow::Result<()> {
description: String,
}
- let mut linter = LintGroup::new(linting_options, dictionary);
- linter.config.fill_default_values();
+ let mut linter = LintGroup::new_curated(linting_options, dictionary);
+ linter.config.fill_with_curated_config();
let default_config: HashMap<String, bool> =
serde_json::from_str(&serde_json::to_string(&linter.config).unwrap()).unwrap();
diff --git a/harper-comments/tests/language_support.rs b/harper-comments/tests/language_support.rs
index 2cf3cf283..8602580a9 100644
--- a/harper-comments/tests/language_support.rs
+++ b/harper-comments/tests/language_support.rs
@@ -25,7 +25,7 @@ macro_rules! create_test {
let dict = FstDictionary::curated();
let document = Document::new(&source, &parser, &dict);
- let mut linter = LintGroup::new(
+ let mut linter = LintGroup::new_curated(
LintGroupConfig::default(),
dict
);
diff --git a/harper-core/benches/parse_demo.rs b/harper-core/benches/parse_demo.rs
index 3f647e58d..c9739072c 100644
--- a/harper-core/benches/parse_demo.rs
+++ b/harper-core/benches/parse_demo.rs
@@ -12,7 +12,7 @@ fn parse_demo(c: &mut Criterion) {
fn lint_demo(c: &mut Criterion) {
let dictionary = FstDictionary::curated();
- let mut lint_set = LintGroup::new(Default::default(), dictionary);
+ let mut lint_set = LintGroup::new_curated(Default::default(), dictionary);
let document = Document::new_markdown_default_curated(black_box(DEMO));
c.bench_function("lint_demo", |b| {
@@ -24,7 +24,8 @@ fn lint_demo_uncached(c: &mut Criterion) {
c.bench_function("lint_demo_uncached", |b| {
b.iter(|| {
let dictionary = FstDictionary::curated();
- let mut lint_set = LintGroup::new(LintGroupConfig::default(), dictionary.clone());
+ let mut lint_set =
+ LintGroup::new_curated(LintGroupConfig::default(), dictionary.clone());
let document = Document::new_markdown_default(black_box(DEMO), &dictionary);
lint_set.lint(&document)
})
diff --git a/harper-core/src/ignored_lints/mod.rs b/harper-core/src/ignored_lints/mod.rs
index 6846baeea..15de80f57 100644
--- a/harper-core/src/ignored_lints/mod.rs
+++ b/harper-core/src/ignored_lints/mod.rs
@@ -68,7 +68,8 @@ mod tests {
let document = Document::new_markdown_default_curated(&text);
let mut lints =
- LintGroup::new(LintGroupConfig::default(), FstDictionary::curated()).lint(&document);
+ LintGroup::new_curated(LintGroupConfig::default(), FstDictionary::curated())
+ .lint(&document);
let mut ignored = IgnoredLints::new();
@@ -85,7 +86,8 @@ mod tests {
let document = Document::new_markdown_default_curated(&text);
let mut lints =
- LintGroup::new(LintGroupConfig::default(), FstDictionary::curated()).lint(&document);
+ LintGroup::new_curated(LintGroupConfig::default(), FstDictionary::curated())
+ .lint(&document);
let Some(first) = lints.first().cloned() else {
return TestResult::discard();
@@ -104,7 +106,8 @@ mod tests {
let document = Document::new_markdown_default_curated(&source);
let mut lints =
- LintGroup::new(LintGroupConfig::default(), FstDictionary::curated()).lint(&document);
+ LintGroup::new_curated(LintGroupConfig::default(), FstDictionary::curated())
+ .lint(&document);
let nth = lints.get(nth_lint).cloned().unwrap_or_else(|| {
panic!("If ignoring the lint at {nth_lint}, make sure there are enough problems.")
diff --git a/harper-core/src/lib.rs b/harper-core/src/lib.rs
index 1f4fabe24..e7b13dd8c 100644
--- a/harper-core/src/lib.rs
+++ b/harper-core/src/lib.rs
@@ -84,9 +84,9 @@ mod tests {
let doc = Document::new_plain_english_curated("Ths tet");
let mut lint_config = LintGroupConfig::default();
- lint_config.fill_default_values();
+ lint_config.fill_with_curated_config();
- let mut linter = LintGroup::new(lint_config, FstDictionary::curated());
+ let mut linter = LintGroup::new_curated(lint_config, FstDictionary::curated());
let mut lints = linter.lint(&doc);
diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rs
index b5630e859..91147ce21 100644
--- a/harper-core/src/linting/lint_group.rs
+++ b/harper-core/src/linting/lint_group.rs
@@ -36,19 +36,6 @@ use super::multiple_sequential_pronouns::MultipleSequentialPronouns;
use super::nobody::Nobody;
use super::number_suffix_capitalization::NumberSuffixCapitalization;
use super::out_of_date::OutOfDate;
-use super::phrase_corrections::BaitedBreath;
-use super::phrase_corrections::BareInMind;
-use super::phrase_corrections::EludedTo;
-use super::phrase_corrections::FaceFirst;
-use super::phrase_corrections::FastPaste;
-use super::phrase_corrections::MutePoint;
-use super::phrase_corrections::StateOfTheArt;
-use super::phrase_corrections::WantBe;
-use super::phrase_corrections::{
- AndTheLike, BadRap, BatedBreath, BeckAndCall, ChangeTack, EnMasse, HumanLife, HungerPang,
- LetAlone, LoAndBehold, NeedHelp, NoLonger, OfCourse, SneakingSuspicion, SpecialAttention,
- SupposedTo, ThanOthers, ThatChallenged, TurnItOff,
-};
use super::pique_interest::PiqueInterest;
use super::plural_conjugate::PluralConjugate;
use super::possessive_your::PossessiveYour;
@@ -78,9 +65,9 @@ use super::wordpress_dotcom::WordPressDotcom;
use super::wrong_quotes::WrongQuotes;
use super::Lint;
use super::{CurrencyPlacement, Linter, NoOxfordComma, OxfordComma};
+use crate::linting::phrase_corrections;
use crate::Dictionary;
use crate::Document;
-use crate::MutableDictionary;
#[derive(Debug, Serialize, Deserialize, Default, Clone)]
#[serde(transparent)]
@@ -93,6 +80,12 @@ impl LintGroupConfig {
self.inner.insert(key.to_string(), val);
}
+ /// Remove any configuration attached to a rule.
+ /// This allows it to assume its default (curated) state.
+ pub fn unset_rule_enabled(&mut self, key: impl AsRef<str>) {
+ self.inner.remove_entry(key.as_ref());
+ }
+
pub fn set_rule_enabled_if_unset(&mut self, key: impl AsRef<str>, val: bool) {
if self.inner.get(key.as_ref()).is_none() {
self.set_rule_enabled(key.as_ref().to_string(), val);
@@ -103,7 +96,15 @@ impl LintGroupConfig {
self.inner.get(key).cloned().unwrap_or(false)
}
- pub fn fill_default_values(&mut self) {
+ /// Merge the contents of another [`LintGroupConfig`] into this one.
+ /// The other config will be left empty after this operation.
+ ///
+ /// Conflicting keys will be overridden by the value in the other group.
+ pub fn merge_from(&mut self, other: &mut LintGroupConfig) {
+ self.inner.extend(other.inner.drain());
+ }
+
+ pub fn fill_with_curated_config(&mut self) {
self.set_rule_enabled_if_unset(stringify!(WordPressDotcom), true);
self.set_rule_enabled_if_unset(stringify!(DayOneNames), true);
self.set_rule_enabled_if_unset(stringify!(PocketCastsNames), true);
@@ -113,18 +114,10 @@ impl LintGroupConfig {
self.set_rule_enabled_if_unset(stringify!(Desktop), true);
self.set_rule_enabled_if_unset(stringify!(Laptop), true);
self.set_rule_enabled_if_unset(stringify!(ThenThan), true);
- self.set_rule_enabled_if_unset(stringify!(MutePoint), true);
self.set_rule_enabled_if_unset(stringify!(PiqueInterest), true);
- self.set_rule_enabled_if_unset(stringify!(BareInMind), true);
- self.set_rule_enabled_if_unset(stringify!(BaitedBreath), true);
- self.set_rule_enabled_if_unset(stringify!(EludedTo), true);
self.set_rule_enabled_if_unset(stringify!(WasAloud), true);
self.set_rule_enabled_if_unset(stringify!(HyphenateNumberDay), true);
- self.set_rule_enabled_if_unset(stringify!(FaceFirst), true);
self.set_rule_enabled_if_unset(stringify!(LeftRightHand), true);
- self.set_rule_enabled_if_unset(stringify!(FastPaste), true);
- self.set_rule_enabled_if_unset(stringify!(StateOfTheArt), true);
- self.set_rule_enabled_if_unset(stringify!(WantBe), true);
self.set_rule_enabled_if_unset(stringify!(HopHope), true);
self.set_rule_enabled_if_unset(stringify!(Furthermore), true);
self.set_rule_enabled_if_unset(stringify!(Overnight), true);
@@ -220,30 +213,13 @@ impl LintGroupConfig {
self.set_rule_enabled_if_unset(stringify!(LetsConfusion), true);
self.set_rule_enabled_if_unset(stringify!(DespiteOf), true);
self.set_rule_enabled_if_unset(stringify!(ChockFull), true);
- self.set_rule_enabled_if_unset(stringify!(HumanLife), true);
- self.set_rule_enabled_if_unset(stringify!(NeedHelp), true);
- self.set_rule_enabled_if_unset(stringify!(NoLonger), true);
- self.set_rule_enabled_if_unset(stringify!(ThatChallenged), true);
- self.set_rule_enabled_if_unset(stringify!(TurnItOff), true);
- self.set_rule_enabled_if_unset(stringify!(OfCourse), true);
- self.set_rule_enabled_if_unset(stringify!(AndTheLike), true);
- self.set_rule_enabled_if_unset(stringify!(BadRap), true);
- self.set_rule_enabled_if_unset(stringify!(BatedBreath), true);
- self.set_rule_enabled_if_unset(stringify!(BeckAndCall), true);
- self.set_rule_enabled_if_unset(stringify!(ChangeTack), true);
- self.set_rule_enabled_if_unset(stringify!(HungerPang), true);
- self.set_rule_enabled_if_unset(stringify!(EnMasse), true);
- self.set_rule_enabled_if_unset(stringify!(LetAlone), true);
self.set_rule_enabled_if_unset(stringify!(LoAndBehold), true);
- self.set_rule_enabled_if_unset(stringify!(SneakingSuspicion), true);
- self.set_rule_enabled_if_unset(stringify!(SpecialAttention), true);
self.set_rule_enabled_if_unset(stringify!(Everywhere), true);
- self.set_rule_enabled_if_unset(stringify!(ThanOthers), true);
- self.set_rule_enabled_if_unset(stringify!(SupposedTo), true);
self.set_rule_enabled("SpellCheck", true);
}
}
+#[derive(Default)]
pub struct LintGroup {
pub config: LintGroupConfig,
inner: HashMap<String, Box<dyn Linter>>,
@@ -268,6 +244,24 @@ impl LintGroup {
}
}
+ /// Merge the contents of another [`LintGroup`] into this one.
+ /// The other lint group will be left empty after this operation.
+ pub fn merge_from(&mut self, other: &mut LintGroup) {
+ self.config.merge_from(&mut other.config);
+ self.inner.extend(other.inner.drain());
+ }
+
+ /// Set all contained rules to a specific value.
+ /// Passing `None` will unset that rule, allowing it to assume its default state.
+ pub fn set_all_rules_to(&mut self, enabled: Option<bool>) {
+ for key in self.inner.keys() {
+ match enabled {
+ Some(v) => self.config.set_rule_enabled(key, v),
+ None => self.config.unset_rule_enabled(key),
+ }
+ }
+ }
+
pub fn all_descriptions(&self) -> HashMap<&str, &str> {
self.inner
.iter()
@@ -275,7 +269,7 @@ impl LintGroup {
.collect()
}
- pub fn new(config: LintGroupConfig, dictionary: impl Dictionary + 'static) -> Self {
+ pub fn new_curated(config: LintGroupConfig, dictionary: impl Dictionary + 'static) -> Self {
let mut out = Self::empty();
macro_rules! insert_struct_rule {
@@ -284,6 +278,8 @@ impl LintGroup {
};
}
+ out.merge_from(&mut phrase_corrections::lint_group());
+
insert_struct_rule!(WordPressDotcom);
insert_struct_rule!(DayOneNames);
insert_struct_rule!(PocketCastsNames);
@@ -293,18 +289,10 @@ impl LintGroup {
insert_struct_rule!(Desktop);
insert_struct_rule!(Laptop);
insert_struct_rule!(ThenThan);
- insert_struct_rule!(MutePoint);
insert_struct_rule!(PiqueInterest);
- insert_struct_rule!(BareInMind);
- insert_struct_rule!(BaitedBreath);
- insert_struct_rule!(EludedTo);
insert_struct_rule!(WasAloud);
insert_struct_rule!(HyphenateNumberDay);
- insert_struct_rule!(FaceFirst);
insert_struct_rule!(LeftRightHand);
- insert_struct_rule!(FastPaste);
- insert_struct_rule!(StateOfTheArt);
- insert_struct_rule!(WantBe);
insert_struct_rule!(HopHope);
insert_struct_rule!(Furthermore);
insert_struct_rule!(Overnight);
@@ -400,26 +388,7 @@ impl LintGroup {
insert_struct_rule!(LetsConfusion);
insert_struct_rule!(DespiteOf);
insert_struct_rule!(ChockFull);
- insert_struct_rule!(HumanLife);
- insert_struct_rule!(NeedHelp);
- insert_struct_rule!(NoLonger);
- insert_struct_rule!(ThatChallenged);
- insert_struct_rule!(TurnItOff);
- insert_struct_rule!(OfCourse);
- insert_struct_rule!(AndTheLike);
- insert_struct_rule!(BadRap);
- insert_struct_rule!(BatedBreath);
- insert_struct_rule!(BeckAndCall);
- insert_struct_rule!(ChangeTack);
- insert_struct_rule!(HungerPang);
- insert_struct_rule!(EnMasse);
- insert_struct_rule!(LetAlone);
- insert_struct_rule!(LoAndBehold);
- insert_struct_rule!(SneakingSuspicion);
- insert_struct_rule!(SpecialAttention);
insert_struct_rule!(Everywhere);
- insert_struct_rule!(ThanOthers);
- insert_struct_rule!(SupposedTo);
out.add("SpellCheck", Box::new(SpellCheck::new(dictionary)));
@@ -434,7 +403,7 @@ impl Linter for LintGroup {
let mut results = Vec::new();
let mut config = self.config.clone();
- config.fill_default_values();
+ config.fill_with_curated_config();
for (key, linter) in &mut self.inner {
if config.is_rule_enabled(key) {
@@ -450,12 +419,6 @@ impl Linter for LintGroup {
}
}
-impl Default for LintGroup {
- fn default() -> Self {
- Self::new(Default::default(), MutableDictionary::default())
- }
-}
-
#[cfg(test)]
mod tests {
use crate::{linting::Linter, Document, FstDictionary, MutableDictionary};
@@ -464,13 +427,15 @@ mod tests {
#[test]
fn can_get_all_descriptions() {
- let group = LintGroup::new(LintGroupConfig::default(), MutableDictionary::default());
+ let group =
+ LintGroup::new_curated(LintGroupConfig::default(), MutableDictionary::default());
group.all_descriptions();
}
#[test]
fn lint_descriptions_are_clean() {
- let mut group = LintGroup::new(LintGroupConfig::default(), FstDictionary::curated());
+ let mut group =
+ LintGroup::new_curated(LintGroupConfig::default(), FstDictionary::curated());
let pairs: Vec<_> = group
.all_descriptions()
.into_iter()
diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rs
index 196ce0a77..f4f2f5f7a 100644
--- a/harper-core/src/linting/mod.rs
+++ b/harper-core/src/linting/mod.rs
@@ -101,19 +101,6 @@ pub use number_suffix_capitalization::NumberSuffixCapitalization;
pub use out_of_date::OutOfDate;
pub use oxford_comma::OxfordComma;
pub use pattern_linter::PatternLinter;
-pub use phrase_corrections::BaitedBreath;
-pub use phrase_corrections::BareInMind;
-pub use phrase_corrections::EludedTo;
-pub use phrase_corrections::FaceFirst;
-pub use phrase_corrections::FastPaste;
-pub use phrase_corrections::MutePoint;
-pub use phrase_corrections::StateOfTheArt;
-pub use phrase_corrections::WantBe;
-pub use phrase_corrections::{
- AndTheLike, BadRap, BatedBreath, BeckAndCall, ChangeTack, EnMasse, HumanLife, HungerPang,
- LetAlone, LoAndBehold, NeedHelp, NoLonger, OfCourse, SneakingSuspicion, SpecialAttention,
- SupposedTo, ThanOthers, ThatChallenged, TurnItOff,
-};
pub use pique_interest::PiqueInterest;
pub use plural_conjugate::PluralConjugate;
pub use possessive_your::PossessiveYour;
diff --git a/harper-core/src/linting/phrase_corrections.rs b/harper-core/src/linting/phrase_corrections.rs
index 8a9667fcf..a589f4418 100644
--- a/harper-core/src/linting/phrase_corrections.rs
+++ b/harper-core/src/linting/phrase_corrections.rs
@@ -1,183 +1,278 @@
-use super::{Lint, LintKind, PatternLinter};
+use super::{Lint, LintGroup, LintKind, PatternLinter};
use crate::linting::Suggestion;
use crate::patterns::{ExactPhrase, OwnedPatternExt, Pattern, SimilarToPhrase};
use crate::{Token, TokenStringExt};
-macro_rules! create_linter_map_phrase {
- ($name:ident, $pattern:expr, $($correct_form:literal).*, $message:expr, $description:expr) => {
- #[doc = $description]
- pub struct $name {
- pattern: Box<dyn Pattern>,
- }
+struct MapPhraseLinter {
+ description: String,
+ pattern: Box<dyn Pattern>,
+ correct_forms: Vec<String>,
+ message: String,
+}
- impl $name {
- pub fn new() -> Self {
- Self {
- pattern: Box::new($pattern),
- }
- }
+impl MapPhraseLinter {
+ pub fn new(
+ pattern: Box<dyn Pattern>,
+ correct_forms: impl IntoIterator<Item = impl ToString>,
+ message: impl ToString,
+ description: impl ToString,
+ ) -> Self {
+ Self {
+ description: description.to_string(),
+ pattern,
+ correct_forms: correct_forms.into_iter().map(|f| f.to_string()).collect(),
+ message: message.to_string(),
}
+ }
- impl Default for $name {
- fn default() -> Self {
- Self::new()
- }
- }
+ pub fn new_similar_to_phrase(phrase: &'static str, detectable_distance: u8) -> Self {
+ Self::new(
+ Box::new(SimilarToPhrase::from_phrase(phrase, detectable_distance)),
+ [phrase],
+ format!("Did you mean the phrase `{phrase}`?"),
+ format!("Looks for slight improper modifications to the phrase `{phrase}`."),
+ )
+ }
+}
+
+impl PatternLinter for MapPhraseLinter {
+ fn pattern(&self) -> &dyn Pattern {
+ self.pattern.as_ref()
+ }
- impl PatternLinter for $name {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
- }
-
- fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Lint {
- let span = matched_tokens.span().unwrap();
- let matched_text = span.get_content(source);
-
- Lint {
- span,
- lint_kind: LintKind::Miscellaneous,
- suggestions: vec![$(
- Suggestion::replace_with_match_case(
- $correct_form.chars().collect(),
- matched_text,
- ),
- )*],
- message: $message.to_string(),
- priority: 31,
- }
- }
-
- fn description(&self) -> &'static str {
- $description
- }
+ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Lint {
+ let span = matched_tokens.span().unwrap();
+ let matched_text = span.get_content(source);
+
+ Lint {
+ span,
+ lint_kind: LintKind::Miscellaneous,
+ suggestions: self
+ .correct_forms
+ .iter()
+ .map(|correct_form| {
+ Suggestion::replace_with_match_case(
+ correct_form.chars().collect(),
+ matched_text,
+ )
+ })
+ .collect(),
+ message: self.message.to_string(),
+ priority: 31,
}
- };
-}
+ }
-/// Generate a linter that will look for a common phrase and correct mild errors that
-/// are still composed of real words.
-macro_rules! create_linter_for_phrase {
- ($name:ident, $correct_form:literal, $dist:literal) => {
- create_linter_map_phrase!(
- $name,
- SimilarToPhrase::from_phrase($correct_form, $dist),
- $correct_form,
- concat!("Did you mean the phrase `", $correct_form, "`?"),
- concat!(
- "Looks for slight improper modifications to the phrase `",
- $correct_form,
- "`."
- )
- );
- };
+ fn description(&self) -> &str {
+ self.description.as_str()
+ }
}
-create_linter_for_phrase!(TurnItOff, "turn it off", 1);
-create_linter_for_phrase!(HumanLife, "human life", 1);
-create_linter_for_phrase!(ThatChallenged, "that challenged", 2);
-create_linter_for_phrase!(NoLonger, "no longer", 1);
-create_linter_for_phrase!(NeedHelp, "need help", 1);
-create_linter_for_phrase!(OfCourse, "of course", 1);
-create_linter_for_phrase!(AndTheLike, "and the like", 1);
-create_linter_for_phrase!(BadRap, "bad rap", 1);
-create_linter_for_phrase!(BatedBreath, "bated breath", 1);
-create_linter_for_phrase!(BeckAndCall, "beck and call", 1);
-create_linter_for_phrase!(HungerPang, "hunger pang", 2);
-create_linter_for_phrase!(EnMasse, "en masse", 1);
-create_linter_for_phrase!(LetAlone, "let alone", 1);
-create_linter_for_phrase!(SneakingSuspicion, "sneaking suspicion", 3);
-create_linter_for_phrase!(SpecialAttention, "special attention", 1);
-create_linter_for_phrase!(ThanOthers, "than others", 1);
-create_linter_for_phrase!(SupposedTo, "supposed to", 1);
-
-create_linter_map_phrase!(LoAndBehold, ExactPhrase::from_phrase("long and behold"), "lo and behold", "Did you mean `lo and behold`?", "Detects the exact phrase `long and behold` and suggests replacing it with the idiomatically correct `lo and behold`");
-create_linter_map_phrase!(
- ChangeTack,
- ExactPhrase::from_phrase("change tact"),
- "change tack",
- "Did you mean the sailing idiom?",
- "Locates minor errors in the sailing idiom `change tack`."
-);
-create_linter_map_phrase!(WantBe, ExactPhrase::from_phrase("want be"),"won't be"."want to be","Did you mean `won't be` or `want to be`?", "Detects incorrect usage of `want be` and suggests `won't be` or `want to be` based on context.");
-create_linter_map_phrase!(StateOfTheArt, ExactPhrase::from_phrase("state of art"), "state of the art", "Did you mean `state of the art`?", "Detects incorrect usage of `state of art` and suggests `state of the art` as the correct phrase.");
-create_linter_map_phrase!(FastPaste, ExactPhrase::from_phrase("fast paste").or(Box::new(ExactPhrase::from_phrase("fast-paste"))), "fast-paced", "Did you mean `fast-paced`?", "Detects incorrect usage of `fast paste` or `fast-paste` and suggests `fast-paced` as the correct phrase.");
-
-create_linter_map_phrase!(
- FaceFirst,
- ExactPhrase::from_phrase("face first into"),
- "Should this be `face-first`?",
- "face-first into",
- "Ensures `face first` is correctly hyphenated as `face-first` when used before `into`."
+/// Produce a [`LintGroup`] that represents all the linters in this module.
+/// Comes pre-configured with the recommended default settings.
+pub fn lint_group() -> LintGroup {
+ let mut group = LintGroup::default();
+
+ group.add(
+ "TurnItOff",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("turn it off", 1)),
+ );
+ group.add(
+ "HumanLife",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("human life", 1)),
+ );
+ group.add(
+ "ThatChallenged",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("that challenged", 2)),
+ );
+ group.add(
+ "NoLonger",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("no longer", 1)),
+ );
+ group.add(
+ "NeedHelp",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("need help", 1)),
+ );
+ group.add(
+ "OfCourse",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("of course", 1)),
+ );
+ group.add(
+ "AndTheLike",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("and the like", 1)),
+ );
+ group.add(
+ "BadRap",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("bad rap", 1)),
+ );
+ group.add(
+ "BatedBreath",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("bated breath", 1)),
+ );
+ group.add(
+ "BeckAndCall",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("beck and call", 1)),
+ );
+ group.add(
+ "HungerPang",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("hunger pang", 2)),
+ );
+ group.add(
+ "EnMasse",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("en masse", 1)),
+ );
+ group.add(
+ "LetAlone",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("let alone", 1)),
+ );
+ group.add(
+ "SneakingSuspicion",
+ Box::new(MapPhraseLinter::new_similar_to_phrase(
+ "sneaking suspicion",
+ 3,
+ )),
+ );
+ group.add(
+ "SpecialAttention",
+ Box::new(MapPhraseLinter::new_similar_to_phrase(
+ "special attention",
+ 1,
+ )),
+ );
+ group.add(
+ "SupposedTo",
+ Box::new(MapPhraseLinter::new_similar_to_phrase("supposed to", 1)),
+ );
+
+ group.add(
+ "ChangeTack",
+ Box::new(MapPhraseLinter::new(
+ Box::new(ExactPhrase::from_phrase("change tact")),
+ ["change tack"],
+ "Did you mean the sailing idiom?",
+ "Locates minor errors in the sailing idiom `change tack`.",
+ )),
+ );
+ group.add(
+ "WantBe",
+ Box::new(MapPhraseLinter::new(
+ Box::new(ExactPhrase::from_phrase("want be")),
+ ["won't be", "want to be"],
+ "Did you mean `won't be` or `want to be`?",
+ "Detects incorrect usage of `want be` and suggests `won't be` or `want to be` based on context."
+ ))
);
-create_linter_map_phrase!(
- EludedTo,
- ExactPhrase::from_phrase("eluded to"),
- "alluded to",
- "Did you mean `alluded to`?",
- "Corrects `eluded to` to `alluded to` in contexts referring to indirect references."
+ group.add(
+ "StateOfTheArt",
+ Box::new(MapPhraseLinter::new(
+ Box::new(ExactPhrase::from_phrase("state of art")),
+ ["state of the art"],
+ "Did you mean `state of the art`?",
+ "Detects incorrect usage of `state of art` and suggests `state of the art` as the correct phrase."
+ ))
);
-create_linter_map_phrase!(
- BaitedBreath,
- ExactPhrase::from_phrase("baited breath"),
- "bated breath",
- "Did you mean `bated breath`?",
- "Ensures `bated breath` is written correctly, as `baited breath` is incorrect."
+ group.add(
+ "FastPaste",
+ Box::new(MapPhraseLinter::new(
+ Box::new(ExactPhrase::from_phrase("fast paste").or(Box::new(ExactPhrase::from_phrase("fast-paste")))),
+ ["fast-paced"],
+ "Did you mean `fast-paced`?",
+ "Detects incorrect usage of `fast paste` or `fast-paste` and suggests `fast-paced` as the correct phrase."
+ ))
);
-create_linter_map_phrase!(
- BareInMind,
- ExactPhrase::from_phrase("bare in mind"),
- "bear in mind",
- "Did you mean `bear in mind`?",
- "Ensures the phrase `bear in mind` is used correctly instead of `bare in mind`."
-);
+ group.add(
+ "FaceFirst",
+ Box::new(MapPhraseLinter::new(
+ Box::new(ExactPhrase::from_phrase("face first into")),
+ ["face-first into"],
+ "Should this be `face-first`?",
+ "Ensures `face first` is correctly hyphenated as `face-first` when used before `into`.",
+ )),
+ );
+
+ group.add(
+ "EludedTo",
+ Box::new(MapPhraseLinter::new(
+ Box::new(ExactPhrase::from_phrase("eluded to")),
+ ["alluded to"],
+ "Did you mean `alluded to`?",
+ "Corrects `eluded to` to `alluded to` in contexts referring to indirect references.",
+ )),
+ );
+
+ group.add(
+ "BaitedBreath",
+ Box::new(MapPhraseLinter::new(
+ Box::new(ExactPhrase::from_phrase("baited breath")),
+ ["bated breath"],
+ "Did you mean `bated breath`?",
+ "Ensures `bated breath` is written correctly, as `baited breath` is incorrect.",
+ )),
+ );
+
+ group.add(
+ "BareInMind",
+ Box::new(MapPhraseLinter::new(
+ Box::new(ExactPhrase::from_phrase("bare in mind")),
+ ["bear in mind"],
+ "Did you mean `bear in mind`?",
+ "Ensures the phrase `bear in mind` is used correctly instead of `bare in mind`.",
+ )),
+ );
+
+ group.add(
+ "MutePoint",
+ Box::new(MapPhraseLinter::new(
+ Box::new(ExactPhrase::from_phrase("mute point")),
+ ["moot point"],
+ "Did you mean `moot point`?",
+ "Ensures `moot point` is used instead of `mute point`, as `moot` means debatable or irrelevant."
+ ))
+ );
+
+ group.set_all_rules_to(Some(true));
-create_linter_map_phrase!(MutePoint, ExactPhrase::from_phrase("mute point"),
- "moot point",
- "Did you mean `moot point`?",
- "Ensures `moot point` is used instead of `mute point`, as `moot` means debatable or irrelevant.");
+ group
+}
#[cfg(test)]
mod tests {
use crate::linting::tests::{assert_lint_count, assert_suggestion_result};
- use super::{
- BadRap, BatedBreath, ChangeTack, EnMasse, HungerPang, LetAlone, LoAndBehold, OfCourse,
- SneakingSuspicion, SpecialAttention, SupposedTo, ThanOthers, TurnItOff,
- };
+ use super::lint_group;
#[test]
fn issue_574() {
- assert_lint_count("run by one", TurnItOff::default(), 0);
+ assert_lint_count("run by one", lint_group(), 0);
}
#[test]
fn turn_it_off_clean_lower() {
- assert_lint_count("turn it off", TurnItOff::default(), 0);
+ assert_lint_count("turn it off", lint_group(), 0);
}
#[test]
fn turn_it_off_clean_upper() {
- assert_lint_count("Turn it off", TurnItOff::default(), 0);
+ assert_lint_count("Turn it off", lint_group(), 0);
}
#[test]
fn of_confusion() {
- assert_suggestion_result("Turn it of", TurnItOff::default(), "Turn it off");
+ assert_suggestion_result("Turn it of", lint_group(), "Turn it off");
}
#[test]
fn i_and_of_confusion() {
- assert_suggestion_result("Turn i of", TurnItOff::default(), "Turn it off");
+ assert_suggestion_result("Turn i of", lint_group(), "Turn it off");
}
#[test]
fn off_course() {
assert_suggestion_result(
"Yes, off course we should do that.",
- OfCourse::default(),
+ lint_group(),
"Yes, of course we should do that.",
);
}
@@ -186,80 +281,58 @@ mod tests {
fn o_course() {
assert_suggestion_result(
"Yes, o course we should do that.",
- OfCourse::default(),
+ lint_group(),
"Yes, of course we should do that.",
);
}
#[test]
fn bad_rep() {
- assert_suggestion_result("bad rep", BadRap::default(), "bad rap");
+ assert_suggestion_result("bad rep", lint_group(), "bad rap");
}
#[test]
fn baited_breath() {
- assert_suggestion_result("baited breath", BatedBreath::default(), "bated breath");
+ assert_suggestion_result("baited breath", lint_group(), "bated breath");
}
#[test]
fn change_tact() {
- assert_suggestion_result("change tact", ChangeTack::default(), "change tack");
+ assert_suggestion_result("change tact", lint_group(), "change tack");
}
#[test]
fn hunger_pain() {
- assert_suggestion_result("hunger pain", HungerPang::default(), "hunger pang");
+ assert_suggestion_result("hunger pain", lint_group(), "hunger pang");
}
#[test]
fn in_mass() {
- assert_suggestion_result("in mass", EnMasse::default(), "en masse");
+ assert_suggestion_result("in mass", lint_group(), "en masse");
}
#[test]
fn let_along() {
- assert_suggestion_result("let along", LetAlone::default(), "let alone");
- }
-
- #[test]
- fn long_and_behold() {
- assert_suggestion_result("long and behold", LoAndBehold::default(), "lo and behold");
+ assert_suggestion_result("let along", lint_group(), "let alone");
}
#[test]
fn sneaky_suspicion() {
- assert_suggestion_result(
- "sneaky suspicion",
- SneakingSuspicion::default(),
- "sneaking suspicion",
- );
+ assert_suggestion_result("sneaky suspicion", lint_group(), "sneaking suspicion");
}
#[test]
fn supposed_to() {
- assert_suggestion_result("suppose to", SupposedTo::default(), "supposed to");
+ assert_suggestion_result("suppose to", lint_group(), "supposed to");
}
#[test]
fn spacial_attention() {
- assert_suggestion_result(
- "spacial attention",
- SpecialAttention::default(),
- "special attention",
- );
- }
-
- #[test]
- fn than_others() {
- assert_suggestion_result("Then others", ThanOthers::default(), "Than others");
+ assert_suggestion_result("spacial attention", lint_group(), "special attention");
}
#[test]
fn now_on_hold() {
- assert_lint_count(
- "Those are now on hold for month.",
- LoAndBehold::default(),
- 0,
- );
+ assert_lint_count("Those are now on hold for month.", lint_group(), 0);
}
}
diff --git a/harper-core/tests/run_tests.rs b/harper-core/tests/run_tests.rs
index 87ac79298..d230b7c4f 100644
--- a/harper-core/tests/run_tests.rs
+++ b/harper-core/tests/run_tests.rs
@@ -18,7 +18,7 @@ macro_rules! create_test {
let dict = FstDictionary::curated();
let document = Document::new_markdown_default(&source, &dict);
- let mut linter = LintGroup::new(
+ let mut linter = LintGroup::new_curated(
LintGroupConfig::default(),
dict
);
diff --git a/harper-html/tests/run_tests.rs b/harper-html/tests/run_tests.rs
index f1c23b3db..495b9e906 100644
--- a/harper-html/tests/run_tests.rs
+++ b/harper-html/tests/run_tests.rs
@@ -18,7 +18,7 @@ macro_rules! create_test {
let dict = FstDictionary::curated();
let document = Document::new_markdown_default(&source, &dict);
- let mut linter = LintGroup::new(
+ let mut linter = LintGroup::new_curated(
LintGroupConfig::default(),
dict
);
diff --git a/harper-literate-haskell/tests/run_tests.rs b/harper-literate-haskell/tests/run_tests.rs
index 7c8e1791a..f0ca14d3d 100644
--- a/harper-literate-haskell/tests/run_tests.rs
+++ b/harper-literate-haskell/tests/run_tests.rs
@@ -20,7 +20,7 @@ macro_rules! create_test {
let dict = FstDictionary::curated();
let document = Document::new_curated(&source, &LiterateHaskellParser::new_markdown(MarkdownOptions::default()));
- let mut linter = LintGroup::new(
+ let mut linter = LintGroup::new_curated(
LintGroupConfig::default(),
dict
);
diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rs
index 16fc625eb..098ae211f 100644
--- a/harper-ls/src/backend.rs
+++ b/harper-ls/src/backend.rs
@@ -158,7 +158,7 @@ impl Backend {
let mut doc_lock = self.doc_state.lock().await;
let doc_state = doc_lock.entry(url.clone()).or_insert(DocumentState {
- linter: LintGroup::new(lint_config.clone(), dict.clone()),
+ linter: LintGroup::new_curated(lint_config.clone(), dict.clone()),
language_id: language_id.map(|v| v.to_string()),
dict: dict.clone(),
url: url.clone(),
@@ -167,7 +167,7 @@ impl Backend {
if doc_state.dict != dict {
doc_state.dict = dict.clone();
- doc_state.linter = LintGroup::new(lint_config.clone(), dict.clone());
+ doc_state.linter = LintGroup::new_curated(lint_config.clone(), dict.clone());
}
let Some(language_id) = &doc_state.language_id else {
@@ -190,7 +190,7 @@ impl Backend {
merged.add_dictionary(new_dict);
let merged = Arc::new(merged);
- doc_state.linter = LintGroup::new(lint_config.clone(), merged.clone());
+ doc_state.linter = LintGroup::new_curated(lint_config.clone(), merged.clone());
doc_state.dict = merged.clone();
}
@@ -588,7 +588,8 @@ impl LanguageServer for Backend {
let config_lock = self.config.read().await;
for doc in doc_lock.values_mut() {
- doc.linter = LintGroup::new(config_lock.lint_config.clone(), doc.dict.clone());
+ doc.linter =
+ LintGroup::new_curated(config_lock.lint_config.clone(), doc.dict.clone());
}
doc_lock.keys().cloned().collect()
diff --git a/harper-typst/tests/run_tests.rs b/harper-typst/tests/run_tests.rs
index b6cba665c..5f1fd8149 100644
--- a/harper-typst/tests/run_tests.rs
+++ b/harper-typst/tests/run_tests.rs
@@ -19,7 +19,7 @@ macro_rules! create_test {
let dict = FstDictionary::curated();
let document = Document::new(&source, &Typst, &dict);
- let mut linter = LintGroup::new(
+ let mut linter = LintGroup::new_curated(
LintGroupConfig::default(),
dict
);
diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rs
index 694a5c3eb..59ba89c14 100644
--- a/harper-wasm/src/lib.rs
+++ b/harper-wasm/src/lib.rs
@@ -82,7 +82,7 @@ impl Linter {
let dictionary = Self::construct_merged_dict(MutableDictionary::default());
Self {
- lint_group: LintGroup::new(LintGroupConfig::default(), dictionary.clone()),
+ lint_group: LintGroup::new_curated(LintGroupConfig::default(), dictionary.clone()),
user_dictionary: MutableDictionary::new(),
dictionary,
ignored_lints: IgnoredLints::default(),
@@ -94,7 +94,7 @@ impl Linter {
fn synchronize_lint_dict(&mut self) {
let lint_config = self.lint_group.config.clone();
self.dictionary = Self::construct_merged_dict(self.user_dictionary.clone());
- self.lint_group = LintGroup::new(lint_config, self.dictionary.clone());
+ self.lint_group = LintGroup::new_curated(lint_config, self.dictionary.clone());
}
/// Construct the actual dictionary to be used for linting and parsing from the curated dictionary
@@ -373,7 +373,7 @@ impl Lint {
#[wasm_bindgen]
pub fn get_default_lint_config_as_json() -> String {
let mut config = LintGroupConfig::default();
- config.fill_default_values();
+ config.fill_with_curated_config();
serde_json::to_string(&config).unwrap()
}
@@ -381,7 +381,7 @@ pub fn get_default_lint_config_as_json() -> String {
#[wasm_bindgen]
pub fn get_default_lint_config() -> JsValue {
let mut config = LintGroupConfig::default();
- config.fill_default_values();
+ config.fill_with_curated_config();
// Important for downstream JSON serialization
let serializer = serde_wasm_bindgen::Serializer::json_compatible();