Skip to content

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

Merge branch 'master' into perf-fixes

Elijah Potter1f6be621f1de
diff --cc harper-core/src/linting/lint_group.rs
index 49e953c16,19f921e18..c807871fb
--- a/harper-core/src/linting/lint_group.rs
+++ b/harper-core/src/linting/lint_group.rs
@@@ -48,221 -77,270 +49,222 @@@ use super::was_aloud::WasAloud
use super::whereas::Whereas;
use super::wordpress_dotcom::WordPressDotcom;
use super::wrong_quotes::WrongQuotes;
-use super::{CurrencyPlacement, Lint, Linter, NoOxfordComma, OxfordComma};
-use crate::{Dictionary, Document};
-
-macro_rules! create_lint_group_config {
- ($($linter:ident => $default:expr),* $(,)?) => {
- paste! {
- /// A collection of all the descriptions from the composing linters.
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
- pub struct LintGroupDescriptions<'a> {
- $(
- #[doc = "The description for the [`" $linter "`] linter."]
- pub [<$linter:snake>]: &'a str,
- )*
- pub spell_check: &'a str
- }
+use super::Lint;
+use super::{CurrencyPlacement, Linter, NoOxfordComma, OxfordComma};
+use crate::linting::{closed_compounds, phrase_corrections};
+use crate::Document;
+use crate::{Dictionary, MutableDictionary};
+#[derive(Debug, Serialize, Deserialize, Default, Clone)]
+#[serde(transparent)]
+pub struct LintGroupConfig {
+ inner: HashMap<String, Option<bool>>,
+}
- impl<'a> LintGroupDescriptions<'a> {
- /// Create a [`Vec`] containing the key-value pairs of this struct.
- pub fn to_vec_pairs(self) -> Vec<(&'static str, &'a str)>{
- vec![$((stringify!([<$linter:snake>]), self.[<$linter:snake>],),)* ("spell_check", self.spell_check)]
- }
- }
+#[cached]
+fn curated_config() -> LintGroupConfig {
+ // Dictionary does not matter, we're just after the config.
+ let group = LintGroup::new_curated(MutableDictionary::new().into());
+ group.config
+}
- /// A collection of all officially supported
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
- pub struct LintGroupConfig {
- $(
- #[doc = "Configures the use of the [`" $linter "`] linter.
- If set to [`None`], the default configuration will be used."]
- pub [<$linter:snake>]: Option<bool>,
- )*
- pub spell_check: Option<bool>
- }
+impl LintGroupConfig {
+ pub fn set_rule_enabled(&mut self, key: impl ToString, val: bool) {
+ self.inner.insert(key.to_string(), Some(val));
+ }
- impl LintGroupConfig {
- /// Creates a config with all lints disabled.
- pub fn none() -> Self{
- Self {
- $(
- [<$linter:snake>]: Some(false),
- )*
- spell_check: Some(false)
- }
- }
-
- /// Fills the [`None`] values in the configuration with the default values.
- pub fn fill_default_values(&mut self){
- $(
- if self.[<$linter:snake>].is_none() {
- self.[<$linter:snake>] = Some($default);
- }
- )*
-
- if self.spell_check.is_none() {
- self.spell_check = Some(true);
- }
- }
- }
+ /// 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());
+ }
- /// A wrapper that combines all built-in Harper linters
- /// into a single, configurable [`Linter`].
- pub struct LintGroup<T: Dictionary> {
- $(
- [<$linter:snake>]: $linter,
- )*
- spell_check: SpellCheck<T>,
- pub config: LintGroupConfig
- }
+ 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);
+ }
+ }
+ pub fn is_rule_enabled(&self, key: &str) -> bool {
+ self.inner.get(key).cloned().flatten().unwrap_or(false)
+ }
- impl<T: Dictionary> LintGroup<T> {
- pub fn new(config: LintGroupConfig, dictionary: T) -> Self {
- Self {
- $(
- [<$linter:snake>]: $linter::default(),
- )*
- spell_check: SpellCheck::new(dictionary),
- config,
- }
- }
-
- pub fn all_descriptions(&self) -> LintGroupDescriptions<'_> {
- LintGroupDescriptions {
- $(
- [<$linter:snake>]: self.[<$linter:snake>].description(),
- )*
- spell_check: self.spell_check.description(),
- }
- }
- }
+ /// Clear all config options.
+ /// This will reset them all to disabled.
+ pub fn clear(&mut self) {
+ for val in self.inner.values_mut() {
+ *val = None
+ }
+ }
- impl<T: Dictionary> Linter for LintGroup<T> {
- fn lint(&mut self, document: &Document) -> Vec<Lint> {
- let mut lints = Vec::new();
+ /// 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());
+ }
- let mut config = self.config.clone();
- config.fill_default_values();
+ /// Fill the group with the values for the curated lint group.
+ pub fn fill_with_curated(&mut self) {
+ self.merge_from(&mut Self::new_curated());
+ }
- $(
- if config.[<$linter:snake>].unwrap() {
- lints.append(&mut self.[<$linter:snake>].lint(document));
- }
- )*
+ pub fn new_curated() -> Self {
+ curated_config()
+ }
+}
- if config.spell_check.unwrap() {
- lints.append(&mut self.spell_check.lint(document));
- }
+#[derive(Default)]
+pub struct LintGroup {
+ pub config: LintGroupConfig,
+ inner: HashMap<String, Box<dyn Linter>>,
+}
+impl LintGroup {
+ pub fn empty() -> Self {
+ Self {
+ config: LintGroupConfig::default(),
+ inner: HashMap::new(),
+ }
+ }
- lints
- }
+ /// Add a [`Linter`] to the group, returning whether the operation was successful.
+ /// If it returns `false`, it is because a linter with that key already existed in the group.
+ pub fn add(&mut self, name: impl AsRef<str>, linter: Box<dyn Linter>) -> bool {
+ if self.inner.contains_key(name.as_ref()) {
+ false
+ } else {
+ self.inner.insert(name.as_ref().to_string(), linter);
+ true
+ }
+ }
- fn description(&self) -> &'static str {
- "A collection of linters that can be run as one."
- }
+ /// 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()
+ .map(|(key, value)| (key.as_str(), value.description()))
+ .collect()
+ }
+
+ /// Swap out [`Self::config`] with another [`LintGroupConfig`].
+ pub fn with_lint_config(mut self, config: LintGroupConfig) -> Self {
+ self.config = config;
+ self
+ }
+
+ pub fn new_curated(dictionary: Arc<impl Dictionary + 'static>) -> Self {
+ let mut out = Self::empty();
+
+ macro_rules! insert_struct_rule {
+ ($rule:ident, $default_config:expr) => {
+ out.add(stringify!($rule), Box::new($rule::default()));
+ out.config
+ .set_rule_enabled(stringify!($rule), $default_config);
+ };
+ }
+
+ out.merge_from(&mut phrase_corrections::lint_group());
+ out.merge_from(&mut proper_noun_capitalization_linters::lint_group(
+ dictionary.clone(),
+ ));
+ out.merge_from(&mut closed_compounds::lint_group());
+
+ // Add all of the more complex rules to the group.
++ insert_struct_rule!(BackInTheDay, true);
+ insert_struct_rule!(WordPressDotcom, true);
+ insert_struct_rule!(OutOfDate, true);
+ insert_struct_rule!(ThenThan, true);
+ insert_struct_rule!(PiqueInterest, true);
+ insert_struct_rule!(WasAloud, true);
+ insert_struct_rule!(HyphenateNumberDay, true);
+ insert_struct_rule!(LeftRightHand, true);
+ insert_struct_rule!(HopHope, true);
+ insert_struct_rule!(Hereby, true);
+ insert_struct_rule!(Likewise, true);
+ insert_struct_rule!(CompoundNouns, true);
+ insert_struct_rule!(Nobody, true);
+ insert_struct_rule!(Whereas, true);
+ insert_struct_rule!(PossessiveYour, true);
+ insert_struct_rule!(SpelledNumbers, false);
+ insert_struct_rule!(AnA, true);
+ insert_struct_rule!(SentenceCapitalization, true);
+ insert_struct_rule!(UnclosedQuotes, true);
+ insert_struct_rule!(WrongQuotes, false);
+ insert_struct_rule!(LongSentences, true);
+ insert_struct_rule!(RepeatedWords, true);
+ insert_struct_rule!(Spaces, true);
+ insert_struct_rule!(Matcher, true);
+ insert_struct_rule!(CorrectNumberSuffix, true);
+ insert_struct_rule!(NumberSuffixCapitalization, true);
+ insert_struct_rule!(MultipleSequentialPronouns, true);
+ insert_struct_rule!(LinkingVerbs, false);
+ insert_struct_rule!(AvoidCurses, true);
+ insert_struct_rule!(TerminatingConjunctions, true);
+ insert_struct_rule!(EllipsisLength, true);
+ insert_struct_rule!(DotInitialisms, true);
+ insert_struct_rule!(BoringWords, false);
+ insert_struct_rule!(UseGenitive, false);
+ insert_struct_rule!(ThatWhich, true);
+ insert_struct_rule!(CapitalizePersonalPronouns, true);
+ insert_struct_rule!(MergeWords, true);
+ insert_struct_rule!(PluralConjugate, false);
+ insert_struct_rule!(OxfordComma, true);
+ insert_struct_rule!(NoOxfordComma, false);
+ insert_struct_rule!(PronounContraction, true);
+ insert_struct_rule!(CurrencyPlacement, true);
+ insert_struct_rule!(SomewhatSomething, true);
+ insert_struct_rule!(LetsConfusion, true);
+ insert_struct_rule!(DespiteOf, true);
+ insert_struct_rule!(ChockFull, true);
+
+ out.add("SpellCheck", Box::new(SpellCheck::new(dictionary)));
+ out.config.set_rule_enabled("SpellCheck", true);
+
+ out
+ }
+
+ /// Create a new curated group with all config values cleared out.
+ pub fn new_curated_empty_config(dictionary: Arc<impl Dictionary + 'static>) -> Self {
+ let mut group = Self::new_curated(dictionary);
+ group.config.clear();
+ group
+ }
}
-create_lint_group_config!(
- BackInTheDay => true,
- WordPressDotcom => true,
- DayOneNames => true,
- PocketCastsNames => true,
- TumblrNames => true,
- JetpackNames => true,
- OutOfDate => true,
- Desktop => true,
- Laptop => true,
- ThenThan => true,
- MutePoint => true,
- PiqueInterest => true,
- BareInMind => true,
- BaitedBreath => true,
- EludedTo => true,
- WasAloud => true,
- HyphenateNumberDay => true,
- FaceFirst => true,
- LeftRightHand => true,
- FastPaste => true,
- StateOfTheArt => true,
- WantBe => true,
- HopHope => true,
- Furthermore => true,
- Overnight => true,
- Hereby => true,
- Likewise => true,
- CompoundNouns => true,
- Regardless => true,
- Henceforth => true,
- Upward => true,
- Whereupon => true,
- Insofar => true,
- Thereupon => true,
- Nonetheless => true,
- Anyhow => true,
- Notwithstanding => true,
- Widespread => true,
- Multimedia => true,
- Multicore => true,
- Multithreading => true,
- Devops => true,
- Underclock => true,
- Overload => true,
- Backplane => true,
- Overclocking => true,
- Middleware => true,
- Somewhere => true,
- Instead => true,
- Anywhere => true,
- Nothing => true,
- Anybody => true,
- Somebody => true,
- Nobody => true,
- Into => true,
- Proofread => true,
- Somehow => true,
- Intact => true,
- Upset => true,
- Misunderstood => true,
- However => true,
- Overall => true,
- Worldwide => true,
- Postpone => true,
- Misused => true,
- Misuse => true,
- Misunderstand => true,
- Therefore => true,
- Myself => true,
- Itself => true,
- Whereas => true,
- PossessiveYour => true,
- SpelledNumbers => false,
- AnA => true,
- SentenceCapitalization => true,
- UnclosedQuotes => true,
- WrongQuotes => false,
- LongSentences => true,
- RepeatedWords => true,
- Spaces => true,
- Matcher => true,
- CorrectNumberSuffix => true,
- NumberSuffixCapitalization => true,
- MultipleSequentialPronouns => true,
- LinkingVerbs => false,
- AvoidCurses => true,
- TerminatingConjunctions => true,
- EllipsisLength => true,
- DotInitialisms => true,
- BoringWords => false,
- UseGenitive => false,
- ThatWhich => true,
- CapitalizePersonalPronouns => true,
- Americas => true,
- Australia => true,
- Canada => true,
- Koreas => true,
- Malaysia => true,
- ChineseCommunistParty => true,
- UnitedOrganizations => true,
- Holidays => true,
- AmazonNames => true,
- GoogleNames => true,
- MetaNames => true,
- MicrosoftNames => true,
- AppleNames => true,
- AzureNames => true,
- MergeWords => true,
- PluralConjugate => false,
- OxfordComma => true,
- NoOxfordComma => false,
- PronounContraction => true,
- CurrencyPlacement => true,
- SomewhatSomething => true,
- LetsConfusion => true,
- DespiteOf => true,
- ChockFull => true,
- HumanLife => true,
- NeedHelp => true,
- NoLonger => true,
- ThatChallenged => true,
- TurnItOff => true,
- OfCourse => true,
- AndTheLike => true,
- BadRap => true,
- BatedBreath => true,
- BeckAndCall => true,
- ChangeTack => true,
- HungerPang => true,
- EnMasse => true,
- LetAlone => true,
- LoAndBehold => true,
- SneakingSuspicion => true,
- SpecialAttention => true,
- Everywhere => true,
- ThanOthers => true,
- SupposedTo => true
-);
-
-impl<T: Dictionary + Default> Default for LintGroup<T> {
- fn default() -> Self {
- Self::new(LintGroupConfig::default(), T::default())
+impl Linter for LintGroup {
+ fn lint(&mut self, document: &Document) -> Vec<Lint> {
+ let mut results = Vec::new();
+
+ for (key, linter) in &mut self.inner {
+ if self.config.is_rule_enabled(key) {
+ results.extend(linter.lint(document));
+ }
+ }
+
+ results
+ }
+
+ fn description(&self) -> &str {
+ "A collection of linters that can be run as one."
}
}
diff --cc harper-core/src/linting/map_phrase_linter.rs
index c696c9640,000000000..e8cf2120f
mode 100644,000000..100644
--- a/harper-core/src/linting/map_phrase_linter.rs
+++ b/harper-core/src/linting/map_phrase_linter.rs
@@@ -1,96 -1,0 +1,96 @@@
+use super::{Lint, LintKind, PatternLinter};
+use crate::linting::Suggestion;
+use crate::patterns::{ExactPhrase, Pattern, SimilarToPhrase};
+use crate::{Token, TokenStringExt};
+
+pub struct MapPhraseLinter {
+ description: String,
+ pattern: Box<dyn Pattern>,
+ correct_forms: Vec<String>,
+ message: String,
+}
+
+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(),
+ }
+ }
+
+ 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}`."),
+ )
+ }
+
+ pub fn new_exact_phrase(
+ phrase: impl AsRef<str>,
+ correct_forms: impl IntoIterator<Item = impl ToString>,
+ message: impl ToString,
+ description: impl ToString,
+ ) -> Self {
+ Self::new(
+ Box::new(ExactPhrase::from_phrase(phrase.as_ref())),
+ correct_forms,
+ message,
+ description,
+ )
+ }
+
+ pub fn new_closed_compound(phrase: impl AsRef<str>, correct_form: impl ToString) -> Self {
+ let message = format!(
+ "Did you mean the closed compound `{}`?",
+ correct_form.to_string()
+ );
+
+ let description = format!(
+ "Looks for incorrect spacing inside the closed compound `{}`.",
+ correct_form.to_string()
+ );
+
+ Self::new_exact_phrase(phrase, [correct_form], message, description)
+ }
+}
+
+impl PatternLinter for MapPhraseLinter {
+ 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();
++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
++ let span = matched_tokens.span()?;
+ let matched_text = span.get_content(source);
+
- Lint {
++ Some(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,
- }
++ })
+ }
+
+ fn description(&self) -> &str {
+ self.description.as_str()
+ }
+}
diff --cc harper-core/src/linting/merge_words.rs
index f732e63eb,f732e63eb..f9aa9ca56
--- a/harper-core/src/linting/merge_words.rs
+++ b/harper-core/src/linting/merge_words.rs
@@@ -52,7 -52,7 +52,7 @@@ impl Linter for MergeWords
{
lints.push(Lint {
span: Span::new(a.span.start, b.span.end),
-- lint_kind: LintKind::Spelling,
++ lint_kind: LintKind::WordChoice,
suggestions: vec![Suggestion::ReplaceWith(merged_word.to_vec())],
message: "It seems these words would go better together.".to_owned(),
priority: 63,
@@@ -69,7 -69,7 +69,7 @@@
{
lints.push(Lint {
span: Span::new(a.span.start, b.span.end),
-- lint_kind: LintKind::Spelling,
++ lint_kind: LintKind::WordChoice,
suggestions: vec![Suggestion::ReplaceWith(merged_word.to_vec())],
message: "It seems you intended to make this a contraction.".to_owned(),
priority: 63,
diff --cc harper-core/src/linting/proper_noun_capitalization_linters.rs
index a2e2edc18,d77845635..988d634b0
--- a/harper-core/src/linting/proper_noun_capitalization_linters.rs
+++ b/harper-core/src/linting/proper_noun_capitalization_linters.rs
@@@ -5,59 -6,61 +5,59 @@@ use crate::{make_title_case, Dictionary
use crate::{Token, TokenStringExt};
use std::sync::Arc;
-/// A macro that will generate a linter to enforce capitalization of a multi-token proper noun.
-macro_rules! create_linter_for {
- ($name:ident, $pattern:expr, $message:literal) => {
- create_linter_for!($name, $pattern, $message, $message);
- };
- ($name:ident, $pattern:expr, $message:literal, $description:literal) => {
- #[doc = $description]
- pub struct $name {
- pattern: Box<dyn Pattern>,
- dict: Arc<FstDictionary>,
+pub struct ProperNounCapitalizationLinter<D: Dictionary + 'static> {
+ pattern: Box<dyn Pattern>,
+ description: String,
+ dictionary: Arc<D>,
+}
+
+impl<D: Dictionary + 'static> ProperNounCapitalizationLinter<D> {
+ pub fn new(
+ search_for: impl Pattern + 'static,
+ description: impl ToString,
+ dictionary: D,
+ ) -> Self {
+ let dictionary = Arc::new(dictionary);
+
+ Self {
+ pattern: Box::new(IsNotTitleCase::new(
+ Box::new(search_for),
+ dictionary.clone(),
+ )),
+ dictionary: dictionary.clone(),
+ description: description.to_string(),
}
+ }
+}
- impl $name {
- pub fn new() -> Self {
- let dict = FstDictionary::curated();
+impl<D: Dictionary + 'static> PatternLinter for ProperNounCapitalizationLinter<D> {
+ fn pattern(&self) -> &dyn Pattern {
+ self.pattern.as_ref()
+ }
- fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Lint {
- Self {
- pattern: Box::new(IsNotTitleCase::new(Box::new($pattern), dict.clone())),
- dict,
- }
- }
- }
++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
+ let proper = make_title_case(matched_tokens, source, &self.dictionary);
- Lint {
- span: matched_tokens.span().unwrap(),
- impl Default for $name {
- fn default() -> Self {
- Self::new()
- }
- }
++ Some(Lint {
++ span: matched_tokens.span()?,
+ lint_kind: LintKind::Capitalization,
+ suggestions: vec![Suggestion::ReplaceWith(proper)],
+ message: self.description.to_string(),
+ priority: 31,
- }
++ })
+ }
- impl PatternLinter for $name {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
- }
-
- fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
- let proper = make_title_case(matched_tokens, source, &self.dict);
-
- Some(Lint {
- span: matched_tokens.span()?,
- lint_kind: LintKind::Capitalization,
- suggestions: vec![Suggestion::ReplaceWith(proper)],
- message: $message.to_string(),
- priority: 31,
- })
- }
-
- fn description(&self) -> &'static str {
- $description
- }
- }
- };
+ fn description(&self) -> &str {
+ self.description.as_str()
+ }
}
-create_linter_for!(
- Americas,
+pub fn lint_group(dictionary: Arc<impl Dictionary + 'static>) -> LintGroup {
+ let mut group = LintGroup::empty();
+
+ group.add(
+ "Americas",
+ Box::new(ProperNounCapitalizationLinter::new(
SequencePattern::default()
.then(Box::new(WordSet::all(&["South", "North", "Central"])))
.then_whitespace()