Skip to content

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

feat: linter for less worse, least worse, etc. (#1457)

Andrew Dunbarb384fbd83ca8
diff --git a/harper-core/src/expr/first_match_of.rs b/harper-core/src/expr/first_match_of.rs
index 9508b6343..fd6fb9581 100644
--- a/harper-core/src/expr/first_match_of.rs
+++ b/harper-core/src/expr/first_match_of.rs
@@ -11,6 +11,10 @@ pub struct FirstMatchOf {
}
impl FirstMatchOf {
+ pub fn new(exprs: Vec<Box<dyn Expr>>) -> Self {
+ Self { exprs }
+ }
+
pub fn push(&mut self, expr: Box<dyn Expr>) {
self.exprs.push(expr);
}
diff --git a/harper-core/src/expr/mergeable_words.rs b/harper-core/src/expr/mergeable_words.rs
index ff6e9b39e..59e73c081 100644
--- a/harper-core/src/expr/mergeable_words.rs
+++ b/harper-core/src/expr/mergeable_words.rs
@@ -1,9 +1,8 @@
use std::sync::Arc;
-use crate::patterns::WhitespacePattern;
use crate::{CharString, Dictionary, FstDictionary, Span, Token, WordMetadata};
-use super::{Expr, LongestMatchOf, SequenceExpr};
+use super::{Expr, SequenceExpr, SpaceOrHyphen};
type PredicateFn = dyn Fn(Option<&WordMetadata>, Option<&WordMetadata>) -> bool + Send + Sync;
@@ -24,10 +23,7 @@ impl MergeableWords {
Self {
inner: SequenceExpr::default()
.then_any_word()
- .then(LongestMatchOf::new(vec![
- Box::new(WhitespacePattern),
- Box::new(|tok: &Token, _source: &[char]| tok.kind.is_hyphen()),
- ]))
+ .then(SpaceOrHyphen)
.then_any_word(),
dict: FstDictionary::curated(),
predicate: Box::new(predicate),
diff --git a/harper-core/src/expr/mod.rs b/harper-core/src/expr/mod.rs
index c61c6a05d..6930a2e2f 100644
--- a/harper-core/src/expr/mod.rs
+++ b/harper-core/src/expr/mod.rs
@@ -11,6 +11,7 @@ mod reflexive_pronoun;
mod repeating;
mod sequence_expr;
mod similar_to_phrase;
+mod space_or_hyphen;
mod spelled_number_expr;
mod step;
mod time_unit_expr;
@@ -25,6 +26,7 @@ pub use all::All;
pub use anchor_end::AnchorEnd;
pub use anchor_start::AnchorStart;
pub use expr_map::ExprMap;
+pub use first_match_of::FirstMatchOf;
pub use fixed_phrase::FixedPhrase;
pub use longest_match_of::LongestMatchOf;
pub use mergeable_words::MergeableWords;
@@ -33,6 +35,7 @@ pub use reflexive_pronoun::ReflexivePronoun;
pub use repeating::Repeating;
pub use sequence_expr::SequenceExpr;
pub use similar_to_phrase::SimilarToPhrase;
+pub use space_or_hyphen::SpaceOrHyphen;
pub use spelled_number_expr::SpelledNumberExpr;
pub use step::Step;
pub use time_unit_expr::TimeUnitExpr;
diff --git a/harper-core/src/expr/space_or_hyphen.rs b/harper-core/src/expr/space_or_hyphen.rs
new file mode 100644
index 000000000..fb0986c76
--- /dev/null
+++ b/harper-core/src/expr/space_or_hyphen.rs
@@ -0,0 +1,19 @@
+use crate::expr::FirstMatchOf;
+use crate::patterns::WhitespacePattern;
+use crate::{Span, Token};
+
+use super::Expr;
+
+/// Matches either a space or a hyphen, useful for matching compound words.
+#[derive(Default)]
+pub struct SpaceOrHyphen;
+
+impl Expr for SpaceOrHyphen {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ FirstMatchOf::new(vec![
+ Box::new(WhitespacePattern),
+ Box::new(|tok: &Token, _source: &[char]| tok.kind.is_hyphen()),
+ ])
+ .run(cursor, tokens, source)
+ }
+}
diff --git a/harper-core/src/linting/chock_full.rs b/harper-core/src/linting/chock_full.rs
index 28a65dd79..11640fe7e 100644
--- a/harper-core/src/linting/chock_full.rs
+++ b/harper-core/src/linting/chock_full.rs
@@ -1,10 +1,7 @@
use crate::expr::Expr;
-use crate::expr::LongestMatchOf;
use crate::expr::SequenceExpr;
-use crate::{
- Token, TokenStringExt,
- patterns::{WhitespacePattern, WordSet},
-};
+use crate::expr::SpaceOrHyphen;
+use crate::{Token, TokenStringExt, patterns::WordSet};
use super::{ExprLinter, Lint, LintKind, Suggestion};
@@ -18,10 +15,7 @@ impl Default for ChockFull {
expr: Box::new(
SequenceExpr::default()
.then(WordSet::new(&["chalk", "choke"]))
- .then(LongestMatchOf::new(vec![
- Box::new(WhitespacePattern),
- Box::new(|tok: &Token, _source: &[char]| tok.kind.is_hyphen()),
- ]))
+ .then(SpaceOrHyphen)
.then_exact_word("full"),
),
}
diff --git a/harper-core/src/linting/less_worse.rs b/harper-core/src/linting/less_worse.rs
new file mode 100644
index 000000000..0a99728f9
--- /dev/null
+++ b/harper-core/src/linting/less_worse.rs
@@ -0,0 +1,156 @@
+use crate::expr::{Expr, SequenceExpr, SpaceOrHyphen};
+use crate::patterns::WordSet;
+use crate::{CharStringExt, Token, TokenStringExt};
+
+use super::{ExprLinter, Lint, LintKind, Suggestion};
+
+pub struct LessWorse {
+ expr: Box<dyn Expr>,
+}
+
+impl Default for LessWorse {
+ fn default() -> Self {
+ Self {
+ expr: Box::new(
+ SequenceExpr::default()
+ .then(WordSet::new(&["less", "least"]))
+ .then(SpaceOrHyphen)
+ .then(WordSet::new(&["worse", "worst"])),
+ ),
+ }
+ }
+}
+
+impl ExprLinter for LessWorse {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
+ }
+
+ fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
+ if toks.len() != 3 {
+ return None;
+ }
+
+ let span = toks.span()?;
+
+ let how_little = toks[0].span.get_content(src).to_lower();
+ let space_or_hyphen = &toks[1];
+ let how_bad = toks[2].span.get_content(src).to_lower();
+
+ let (suggestions, message): (&[&[char]], &str) = match (
+ how_little.as_ref(),
+ space_or_hyphen.kind.is_hyphen(),
+ how_bad.as_ref(),
+ ) {
+ // "Least worst": Not standard or grammatical but idiomatic and popular.
+ (['l', 'e', 'a', 's', 't'], false, ['w', 'o', 'r', 's', 't']) => (
+ &[&['l', 'e', 'a', 's', 't', ' ', 'b', 'a', 'd']],
+ "Though `least worst` is a common idiom, `least bad` is the standard way to compare bad options.",
+ ),
+ // "Least-worst": As above but also the hyphen is incorrect.
+ (['l', 'e', 'a', 's', 't'], true, ['w', 'o', 'r', 's', 't']) => (
+ &[
+ &['l', 'e', 'a', 's', 't', ' ', 'w', 'o', 'r', 's', 't'],
+ &['l', 'e', 'a', 's', 't', ' ', 'b', 'a', 'd'],
+ ],
+ "`Least worst` (without the hyphen) is a common idiom, but `least bad` is the standard way to compare bad options.",
+ ),
+ // About 1/3 as common as "least worst" so less acceptable as an idiom.
+ (['l', 'e', 's', 's'], _, ['w', 'o', 'r', 's', 'e']) => (
+ &[&['l', 'e', 's', 's', ' ', 'b', 'a', 'd']],
+ "The standard way to compare bad options is `less bad`.",
+ ),
+ // Ambiguous. Is it supposed to be comparative or superlative?
+ (['l', 'e', 's', 's'], _, ['w', 'o', 'r', 's', 't']) => (
+ &[
+ &['l', 'e', 's', 's', ' ', 'b', 'a', 'd'],
+ &['l', 'e', 'a', 's', 't', ' ', 'b', 'a', 'd'],
+ ],
+ "These words conflict with each other. Choose `less bad` or `least bad`.",
+ ),
+ // Ambiguous. Probably a non-native speaker that means "least worst", but offer all three options.
+ (['l', 'e', 'a', 's', 't'], _, ['w', 'o', 'r', 's', 'e']) => (
+ &[
+ &['l', 'e', 'a', 's', 't', ' ', 'w', 'o', 'r', 's', 't'],
+ &['l', 'e', 'a', 's', 't', ' ', 'b', 'a', 'd'],
+ &['l', 'e', 's', 's', ' ', 'b', 'a', 'd'],
+ ],
+ "These words conflict with each other. Choose `less bad` or `least bad` for more standard English, or `least worst` for more idiomatic English.",
+ ),
+ _ => return None,
+ };
+
+ let template = span.get_content(src);
+
+ Some(Lint {
+ span,
+ lint_kind: LintKind::WordChoice,
+ suggestions: suggestions
+ .iter()
+ .map(|s| Suggestion::replace_with_match_case(s.to_vec(), template))
+ .collect::<Vec<_>>(),
+ message: message.to_string(),
+ priority: 126,
+ })
+ }
+
+ fn description(&self) -> &'static str {
+ "Suggests alternatives to `less/least worse/worst` for more standard, clearer comparisons."
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::linting::tests::{assert_good_and_bad_suggestions, assert_top3_suggestion_result};
+
+ use super::LessWorse;
+
+ #[test]
+ fn correct_least_worse() {
+ assert_good_and_bad_suggestions(
+ "Maybe downstream packaging folks could advice what would be least worse option.",
+ LessWorse::default(),
+ &[
+ &"Maybe downstream packaging folks could advice what would be least worst option.",
+ &"Maybe downstream packaging folks could advice what would be least bad option.",
+ &"Maybe downstream packaging folks could advice what would be less bad option.",
+ ],
+ &[],
+ );
+ }
+
+ #[test]
+ fn correct_least_worst_hyphen() {
+ assert_good_and_bad_suggestions(
+ "async-dropper is probably the least-worst ad-hoc AsyncDrop implementation you've seen.",
+ LessWorse::default(),
+ &[
+ &"async-dropper is probably the least worst ad-hoc AsyncDrop implementation you've seen.",
+ &"async-dropper is probably the least bad ad-hoc AsyncDrop implementation you've seen.",
+ ],
+ &[],
+ );
+ }
+
+ #[test]
+ fn correct_less_worse() {
+ assert_top3_suggestion_result(
+ "Professionally I've convinced the team at @Roave to pay me for making their PHP code marginally less worse.",
+ LessWorse::default(),
+ "Professionally I've convinced the team at @Roave to pay me for making their PHP code marginally less bad.",
+ );
+ }
+
+ #[test]
+ fn correct_less_worst() {
+ assert_good_and_bad_suggestions(
+ "May be the less worst choice for some little playlists.",
+ LessWorse::default(),
+ &[
+ &"May be the less bad choice for some little playlists.",
+ &"May be the least bad choice for some little playlists.",
+ ],
+ &[],
+ );
+ }
+}
diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rs
index 71211ceca..143bb84a4 100644
--- a/harper-core/src/linting/lint_group.rs
+++ b/harper-core/src/linting/lint_group.rs
@@ -46,6 +46,7 @@ use super::hyphenate_number_day::HyphenateNumberDay;
use super::inflected_verb_after_to::InflectedVerbAfterTo;
use super::its_contraction::ItsContraction;
use super::left_right_hand::LeftRightHand;
+use super::less_worse::LessWorse;
use super::lets_confusion::LetsConfusion;
use super::likewise::Likewise;
use super::long_sentences::LongSentences;
@@ -399,6 +400,7 @@ impl LintGroup {
insert_pattern_rule!(HyphenateNumberDay, true);
insert_pattern_rule!(ItsContraction, true);
insert_pattern_rule!(LeftRightHand, true);
+ insert_pattern_rule!(LessWorse, true);
insert_struct_rule!(LetsConfusion, true);
insert_pattern_rule!(Likewise, true);
insert_struct_rule!(LongSentences, true);
diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rs
index f989c9364..4444486f8 100644
--- a/harper-core/src/linting/mod.rs
+++ b/harper-core/src/linting/mod.rs
@@ -44,6 +44,7 @@ mod it_is;
mod it_would_be;
mod its_contraction;
mod left_right_hand;
+mod less_worse;
mod lets_confusion;
mod likewise;
mod lint;
@@ -138,6 +139,7 @@ pub use inflected_verb_after_to::InflectedVerbAfterTo;
pub use initialism_linter::InitialismLinter;
pub use its_contraction::ItsContraction;
pub use left_right_hand::LeftRightHand;
+pub use less_worse::LessWorse;
pub use lets_confusion::LetsConfusion;
pub use likewise::Likewise;
pub use lint::Lint;