Skip to content

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

refactor: optimize `FirstMatchOf`/`LongestMatchOf` ctors to accept generic iterators (#3670)

Andrew Dunbar854a7626286e
diff --git a/harper-core/src/expr/first_match_of.rs b/harper-core/src/expr/first_match_of.rs
index c41eb91ca..56c4d3114 100644
--- a/harper-core/src/expr/first_match_of.rs
+++ b/harper-core/src/expr/first_match_of.rs
@@ -1,4 +1,4 @@
-use super::Expr;
+use super::{AsBoxedExpr, Expr};
use crate::{Span, Token};
/// A naive expr collection that naively iterates through a list of patterns,
@@ -11,8 +11,10 @@ pub struct FirstMatchOf {
}
impl FirstMatchOf {
- pub fn new(exprs: Vec<Box<dyn Expr>>) -> Self {
- Self { exprs }
+ pub fn new(exprs: impl IntoIterator<Item = impl AsBoxedExpr>) -> Self {
+ Self {
+ exprs: exprs.into_iter().map(|e| e.into_boxed_expr()).collect(),
+ }
}
pub fn add(&mut self, expr: impl Expr + 'static) {
@@ -20,7 +22,7 @@ impl FirstMatchOf {
}
pub fn add_boxed(&mut self, expr: Box<dyn Expr>) {
- self.exprs.push(Box::new(expr));
+ self.exprs.push(expr);
}
}
diff --git a/harper-core/src/expr/longest_match_of.rs b/harper-core/src/expr/longest_match_of.rs
index d7961b98e..5946121cb 100644
--- a/harper-core/src/expr/longest_match_of.rs
+++ b/harper-core/src/expr/longest_match_of.rs
@@ -1,4 +1,5 @@
-use crate::{Span, Token, expr::Expr};
+use super::{AsBoxedExpr, Expr};
+use crate::{Span, Token};
/// An [`Expr`] that returns the farthest offset of the longest match in a list of expressions.
#[derive(Default)]
@@ -7,8 +8,10 @@ pub struct LongestMatchOf {
}
impl LongestMatchOf {
- pub fn new(exprs: Vec<Box<dyn Expr>>) -> Self {
- Self { exprs }
+ pub fn new(exprs: impl IntoIterator<Item = impl AsBoxedExpr>) -> Self {
+ Self {
+ exprs: exprs.into_iter().map(|e| e.into_boxed_expr()).collect(),
+ }
}
pub fn add(&mut self, expr: impl Expr + 'static) {
diff --git a/harper-core/src/expr/mod.rs b/harper-core/src/expr/mod.rs
index 7553e62df..204b0d3e3 100644
--- a/harper-core/src/expr/mod.rs
+++ b/harper-core/src/expr/mod.rs
@@ -175,12 +175,14 @@ where
{
/// Returns an expression that matches either the current one or the expression contained in `other`.
fn or(self, other: impl Expr + 'static) -> FirstMatchOf {
- FirstMatchOf::new(vec![Box::new(self), Box::new(other)])
+ let exprs: Vec<Box<dyn Expr>> = vec![Box::new(self), Box::new(other)];
+ FirstMatchOf::new(exprs)
}
/// Returns an expression that matches only if both the current one and the expression contained in `other` do.
fn and(self, other: impl Expr + 'static) -> All {
- All::new(vec![Box::new(self), Box::new(other)])
+ let exprs: Vec<Box<dyn Expr>> = vec![Box::new(self), Box::new(other)];
+ All::new(exprs)
}
/// Returns an expression that matches only if the current one matches and the expression contained in `other` does not.
@@ -192,6 +194,39 @@ where
///
/// If you don't need the longest match, prefer using the short-circuiting [`Self::or()`] instead.
fn or_longest(self, other: impl Expr + 'static) -> LongestMatchOf {
- LongestMatchOf::new(vec![Box::new(self), Box::new(other)])
+ let exprs: Vec<Box<dyn Expr>> = vec![Box::new(self), Box::new(other)];
+ LongestMatchOf::new(exprs)
+ }
+}
+
+pub trait IntoBoxedExpr {
+ fn into_boxed(self) -> Box<dyn Expr>;
+}
+
+impl<T: Expr + 'static> IntoBoxedExpr for Box<T> {
+ fn into_boxed(self) -> Box<dyn Expr> {
+ self
+ }
+}
+
+impl IntoBoxedExpr for Box<dyn Expr> {
+ fn into_boxed(self) -> Box<dyn Expr> {
+ self
+ }
+}
+
+pub trait AsBoxedExpr {
+ fn into_boxed_expr(self) -> Box<dyn Expr>;
+}
+
+impl<T: Expr + 'static> AsBoxedExpr for Box<T> {
+ fn into_boxed_expr(self) -> Box<dyn Expr> {
+ self
+ }
+}
+
+impl AsBoxedExpr for Box<dyn Expr> {
+ fn into_boxed_expr(self) -> Box<dyn Expr> {
+ self
}
}
diff --git a/harper-core/src/expr/space_or_hyphen.rs b/harper-core/src/expr/space_or_hyphen.rs
index a77481de3..e3cfdbe49 100644
--- a/harper-core/src/expr/space_or_hyphen.rs
+++ b/harper-core/src/expr/space_or_hyphen.rs
@@ -10,8 +10,8 @@ pub struct SpaceOrHyphen;
impl Expr for SpaceOrHyphen {
fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span<Token>> {
- FirstMatchOf::new(vec![
- Box::new(WhitespacePattern),
+ FirstMatchOf::new([
+ Box::new(WhitespacePattern) as Box<dyn Expr>,
Box::new(|tok: &Token, _source: &[char]| tok.kind.is_hyphen()),
])
.run(cursor, tokens, source)
diff --git a/harper-core/src/expr/spelled_number_expr.rs b/harper-core/src/expr/spelled_number_expr.rs
index e2dc25bd2..a7f2e6a4b 100644
--- a/harper-core/src/expr/spelled_number_expr.rs
+++ b/harper-core/src/expr/spelled_number_expr.rs
@@ -58,8 +58,10 @@ impl Expr for SpelledNumberExpr {
])
.then_word_set(units);
- let expr =
- LongestMatchOf::new(vec![Box::new(single_words), Box::new(tens_units_compounds)]);
+ let expr = LongestMatchOf::new(vec![
+ Box::new(single_words) as Box<dyn Expr>,
+ Box::new(tens_units_compounds),
+ ]);
expr.run(cursor, tokens, source)
}
diff --git a/harper-core/src/linting/addicting.rs b/harper-core/src/linting/addicting.rs
index da4dc9aa5..fe2e10977 100644
--- a/harper-core/src/linting/addicting.rs
+++ b/harper-core/src/linting/addicting.rs
@@ -22,8 +22,8 @@ impl Default for Addicting {
// positive - any word
Box::new(SequenceExpr::any_word()),
// negative - reflexive pronoun or object pronoun
- Box::new(SequenceExpr::unless(FirstMatchOf::new(vec![
- Box::new(ReflexivePronoun::with_common_errors()),
+ Box::new(SequenceExpr::unless(FirstMatchOf::new([
+ Box::new(ReflexivePronoun::with_common_errors()) as Box<dyn Expr>,
Box::new(SequenceExpr::default().then_object_pronoun()),
]))),
]))),
diff --git a/harper-core/src/linting/crave_for.rs b/harper-core/src/linting/crave_for.rs
index 611915416..6b7adfa10 100644
--- a/harper-core/src/linting/crave_for.rs
+++ b/harper-core/src/linting/crave_for.rs
@@ -12,12 +12,12 @@ pub struct CraveFor {
impl Default for CraveFor {
fn default() -> Self {
Self {
- expr: FirstMatchOf::new(vec![
+ expr: FirstMatchOf::new([
Box::new(
SequenceExpr::word_set(&["crave", "craved", "craves"])
.t_ws()
.t_aco("for"),
- ),
+ ) as Box<dyn Expr>,
Box::new(
SequenceExpr::any_of(vec![
Box::new(InflectionOfBe::default()),
diff --git a/harper-core/src/linting/discourse_markers.rs b/harper-core/src/linting/discourse_markers.rs
index 03e0b77d2..f39765bfc 100644
--- a/harper-core/src/linting/discourse_markers.rs
+++ b/harper-core/src/linting/discourse_markers.rs
@@ -44,8 +44,7 @@ impl DiscourseMarkers {
let phrases_expr = FirstMatchOf::new(
phrases
.iter()
- .map(|text: &&str| Box::new(FixedPhrase::from_phrase(text)) as Box<dyn Expr>)
- .collect(),
+ .map(|text: &&str| Box::new(FixedPhrase::from_phrase(text)) as Box<dyn Expr>),
);
Self {
diff --git a/harper-core/src/linting/in_on_the_cards.rs b/harper-core/src/linting/in_on_the_cards.rs
index b28d2398d..3bb04ef35 100644
--- a/harper-core/src/linting/in_on_the_cards.rs
+++ b/harper-core/src/linting/in_on_the_cards.rs
@@ -21,8 +21,8 @@ impl InOnTheCards {
_ => "on",
};
- let pre_context = FirstMatchOf::new(vec![
- Box::new(InflectionOfBe::new()),
+ let pre_context = FirstMatchOf::new([
+ Box::new(InflectionOfBe::new()) as Box<dyn Expr>,
Box::new(WordSet::new(&[
"isn't", "it's", "wasn't", "weren't", "not", "isnt", "its", "wasnt", "werent",
])),
diff --git a/harper-core/src/linting/map_phrase_linter.rs b/harper-core/src/linting/map_phrase_linter.rs
index da5684716..7dd704980 100644
--- a/harper-core/src/linting/map_phrase_linter.rs
+++ b/harper-core/src/linting/map_phrase_linter.rs
@@ -50,15 +50,10 @@ impl MapPhraseLinter {
description: impl ToString,
lint_kind: Option<LintKind>,
) -> Self {
- let patterns = LongestMatchOf::new(
- phrase
- .into_iter()
- .map(|p| {
- let expr: Box<dyn Expr> = Box::new(weir_expr_to_expr(p.as_ref()).unwrap());
- expr
- })
- .collect(),
- );
+ let patterns = LongestMatchOf::new(phrase.into_iter().map(|p| {
+ let expr: Box<dyn Expr> = Box::new(weir_expr_to_expr(p.as_ref()).unwrap());
+ expr
+ }));
Self::new(
Box::new(patterns),
diff --git a/harper-core/src/linting/map_phrase_set_linter.rs b/harper-core/src/linting/map_phrase_set_linter.rs
index fe5d01bb3..76ac15d14 100644
--- a/harper-core/src/linting/map_phrase_set_linter.rs
+++ b/harper-core/src/linting/map_phrase_set_linter.rs
@@ -23,15 +23,12 @@ impl<'a> MapPhraseSetLinter<'a> {
description: impl ToString,
lint_kind: Option<LintKind>,
) -> Self {
- let expr = LongestMatchOf::new(
- wrong_forms_to_correct_forms
- .iter()
- .map(|(wrong_form, _correct_form)| {
- let expr: Box<dyn Expr> = Box::new(FixedPhrase::from_phrase(wrong_form));
- expr
- })
- .collect(),
- );
+ let expr = LongestMatchOf::new(wrong_forms_to_correct_forms.iter().map(
+ |(wrong_form, _correct_form)| {
+ let expr: Box<dyn Expr> = Box::new(FixedPhrase::from_phrase(wrong_form));
+ expr
+ },
+ ));
Self {
description: description.to_string(),
@@ -49,7 +46,7 @@ impl<'a> MapPhraseSetLinter<'a> {
description: impl ToString,
lint_kind: Option<LintKind>,
) -> Self {
- let mut lmo = LongestMatchOf::new(Vec::new());
+ let mut lmo = LongestMatchOf::new(Vec::<Box<dyn Expr>>::new());
for (wrong_forms, _correct_forms) in multi_wrong_forms_to_multi_correct_forms {
for wrong_form in wrong_forms.iter() {
lmo.add(FixedPhrase::from_phrase(wrong_form));
diff --git a/harper-core/src/linting/modal_of.rs b/harper-core/src/linting/modal_of.rs
index 5b195c90b..9da5d903b 100644
--- a/harper-core/src/linting/modal_of.rs
+++ b/harper-core/src/linting/modal_of.rs
@@ -54,7 +54,7 @@ impl Default for ModalOf {
Self {
expr: LongestMatchOf::new(vec![
- Box::new(anyword_might_of_course),
+ Box::new(anyword_might_of_course) as Box<dyn Expr>,
Box::new(modal_of_course),
Box::new(anyword_might_of),
Box::new(noun_will_of_naive),
diff --git a/harper-core/src/linting/months.rs b/harper-core/src/linting/months.rs
index 116872651..a696f11db 100644
--- a/harper-core/src/linting/months.rs
+++ b/harper-core/src/linting/months.rs
@@ -65,8 +65,8 @@ impl Default for Months {
// An Expr that matches either a plain month
// Or an ambiguous month after a disambiguating word
- let month_expr = SequenceExpr::with(FirstMatchOf::new(vec![
- Box::new(only_months),
+ let month_expr = SequenceExpr::with(FirstMatchOf::new([
+ Box::new(only_months) as Box<dyn Expr>,
Box::new(
SequenceExpr::with(before_month_sense_only)
.then_whitespace()
diff --git a/harper-core/src/linting/more_adjective.rs b/harper-core/src/linting/more_adjective.rs
index 924a8b3aa..825b8313e 100644
--- a/harper-core/src/linting/more_adjective.rs
+++ b/harper-core/src/linting/more_adjective.rs
@@ -24,13 +24,13 @@ where
.then_positive_adjective()
// Include a following "than adjective" which we'll use to identify a false positive #2925
// Or a following hyphen which we'll use to identify a false positive #3568
- .then_optional(FirstMatchOf::new(vec![
+ .then_optional(FirstMatchOf::new([
Box::new(
SequenceExpr::whitespace()
.t_aco("than")
.t_ws()
.then_positive_adjective(),
- ),
+ ) as Box<dyn Expr>,
Box::new(|tok: &Token, _source: &[char]| tok.kind.is_hyphen()),
])),
dict,
diff --git a/harper-core/src/linting/need_to_noun.rs b/harper-core/src/linting/need_to_noun.rs
index b4eda1f9b..b8f6466c8 100644
--- a/harper-core/src/linting/need_to_noun.rs
+++ b/harper-core/src/linting/need_to_noun.rs
@@ -19,7 +19,7 @@ impl Default for NeedToNoun {
|| tok.kind.is_determiner()
|| tok.kind.is_unlintable()
|| tok.kind.is_pronoun()
- }),
+ }) as Box<dyn Expr>,
Box::new(WordSet::new(&["about", "into", "it"])),
]);
diff --git a/harper-core/src/linting/no_match_for.rs b/harper-core/src/linting/no_match_for.rs
index 947b2b835..461fcf5fd 100644
--- a/harper-core/src/linting/no_match_for.rs
+++ b/harper-core/src/linting/no_match_for.rs
@@ -12,8 +12,8 @@ pub struct NoMatchFor {
impl Default for NoMatchFor {
fn default() -> Self {
- let pre_context = FirstMatchOf::new(vec![
- Box::new(InflectionOfBe::default()),
+ let pre_context = FirstMatchOf::new([
+ Box::new(InflectionOfBe::default()) as Box<dyn Expr>,
Box::new(WordSet::new(&[
"I'm", "we're", "you're", "he's", "she's", "it's", "they're", "Im", "were",
"youre", "hes", "shes", "its", "theyre",
diff --git a/harper-core/src/linting/noun_verb_confusion/noun_instead_of_verb/general.rs b/harper-core/src/linting/noun_verb_confusion/noun_instead_of_verb/general.rs
index c28ec0e74..b7c909dde 100644
--- a/harper-core/src/linting/noun_verb_confusion/noun_instead_of_verb/general.rs
+++ b/harper-core/src/linting/noun_verb_confusion/noun_instead_of_verb/general.rs
@@ -24,7 +24,7 @@ impl Default for GeneralNounInsteadOfVerb {
};
let pre_context = FirstMatchOf::new(vec![
- Box::new(WordSet::new(PRONOUNS)),
+ Box::new(WordSet::new(PRONOUNS)) as Box<dyn Expr>,
Box::new(ModalVerb::with_common_errors()),
Box::new(WordSet::new(&["do", "don't", "dont"])),
Box::new(adverb_of_frequency),
@@ -52,8 +52,8 @@ impl Default for GeneralNounInsteadOfVerb {
.then_any_word();
Self {
- expr: Box::new(LongestMatchOf::new(vec![
- Box::new(pattern_followed_by_punctuation),
+ expr: Box::new(LongestMatchOf::new([
+ Box::new(pattern_followed_by_punctuation) as Box<dyn Expr>,
Box::new(pattern_followed_by_word),
Box::new(basic_pattern),
])),
diff --git a/harper-core/src/linting/on_floor.rs b/harper-core/src/linting/on_floor.rs
index 595fc3ac5..332518e2e 100644
--- a/harper-core/src/linting/on_floor.rs
+++ b/harper-core/src/linting/on_floor.rs
@@ -40,7 +40,7 @@ impl Default for OnFloor {
]));
let pattern = LongestMatchOf::new(vec![
- Box::new(on_the_floor.clone()),
+ Box::new(on_the_floor.clone()) as Box<dyn Expr>,
Box::new(
SequenceExpr::with(exceptions.clone())
.t_ws()
diff --git a/harper-core/src/linting/open_compounds.rs b/harper-core/src/linting/open_compounds.rs
index ee445dd41..19cb3bfb3 100644
--- a/harper-core/src/linting/open_compounds.rs
+++ b/harper-core/src/linting/open_compounds.rs
@@ -51,7 +51,7 @@ impl Default for OpenCompounds {
Self {
expr: LongestMatchOf::new(vec![
- Box::new(with_prev_and_next),
+ Box::new(with_prev_and_next) as Box<dyn Expr>,
Box::new(with_prev),
Box::new(with_next),
Box::new(compound),
diff --git a/harper-core/src/linting/open_the_light.rs b/harper-core/src/linting/open_the_light.rs
index 01b598774..b289480f5 100644
--- a/harper-core/src/linting/open_the_light.rs
+++ b/harper-core/src/linting/open_the_light.rs
@@ -47,7 +47,7 @@ impl Default for OpenTheLight {
.then_noun();
let expr = LongestMatchOf::new(vec![
- Box::new(open_the_device),
+ Box::new(open_the_device) as Box<dyn Expr>,
Box::new(open_the_device_then_noun),
]);
diff --git a/harper-core/src/linting/redundant_additive_adverbs.rs b/harper-core/src/linting/redundant_additive_adverbs.rs
index 9a66572b9..3d7df9a99 100644
--- a/harper-core/src/linting/redundant_additive_adverbs.rs
+++ b/harper-core/src/linting/redundant_additive_adverbs.rs
@@ -15,8 +15,8 @@ impl Default for RedundantAdditiveAdverbs {
let also_too = WordSet::new(&["also", "too"]);
let as_well = FixedPhrase::from_phrase("as well");
- let additive_adverb = Lrc::new(FirstMatchOf::new(vec![
- Box::new(also_too),
+ let additive_adverb = Lrc::new(FirstMatchOf::new([
+ Box::new(also_too) as Box<dyn Expr>,
Box::new(as_well),
]));
diff --git a/harper-core/src/linting/then_than.rs b/harper-core/src/linting/then_than.rs
index 42741a239..dcca4f14c 100644
--- a/harper-core/src/linting/then_than.rs
+++ b/harper-core/src/linting/then_than.rs
@@ -13,7 +13,7 @@ pub struct ThenThan {
impl ThenThan {
pub fn new() -> Self {
let comparison = All::new(vec![
- Box::new(FirstMatchOf::new(vec![
+ Box::new(FirstMatchOf::new([
// Comparative form of adjective
Box::new(
SequenceExpr::with(Box::new(|tok: &Token, source: &[char]| {
@@ -40,8 +40,8 @@ impl ThenThan {
]);
Self {
- expr: FirstMatchOf::new(vec![
- Box::new(comparison),
+ expr: FirstMatchOf::new([
+ Box::new(comparison) as Box<dyn Expr>,
Box::new(FixedPhrase::from_phrase("easier said then done")),
Box::new(FixedPhrase::from_phrase("now and than")),
Box::new(FixedPhrase::from_phrase("other then")),
diff --git a/harper-core/src/linting/there_is_agreement.rs b/harper-core/src/linting/there_is_agreement.rs
index c5c9c1bc2..e351c0d66 100644
--- a/harper-core/src/linting/there_is_agreement.rs
+++ b/harper-core/src/linting/there_is_agreement.rs
@@ -54,12 +54,12 @@ impl<D: Dictionary> ThereIsAgreement<D> {
// TODO but this rejects "problem"
// "two" etc. are sg. nouns even though they can also be plural quantifiers
let singular_noun = Lrc::new(SequenceExpr::default().then_singular_noun().but_not(
- FirstMatchOf::new(vec![
+ FirstMatchOf::new([
Box::new(|t: &Token, s: &[char]| {
t.kind.is_adjective()
|| t.get_ch(s)
.eq_any_ignore_ascii_case_chars(&[&['n', 'o'], &['n', 'o', 't']])
- }),
+ }) as Box<dyn Expr>,
Box::new(SpelledNumberExpr),
]),
));
diff --git a/harper-core/src/linting/thing_think.rs b/harper-core/src/linting/thing_think.rs
index 0c288a52f..4694508b6 100644
--- a/harper-core/src/linting/thing_think.rs
+++ b/harper-core/src/linting/thing_think.rs
@@ -14,18 +14,18 @@ pub struct ThingThink {
impl Default for ThingThink {
fn default() -> Self {
let subject_pronouns = WordSet::new(&["I", "you", "we", "they"]);
- let indefinite_pronouns = FirstMatchOf::new(vec![
+ let indefinite_pronouns = FirstMatchOf::new([
Box::new(WordSet::new(&[
"anybody",
"anyone",
"everybody",
"everyone",
- ])),
+ ])) as Box<dyn Expr>,
// "Any one thing", "every one thing", "any body thing" cause false positives.
Box::new(FixedPhrase::from_phrase("every body")),
]);
- let pronoun = FirstMatchOf::new(vec![
- Box::new(subject_pronouns),
+ let pronoun = FirstMatchOf::new([
+ Box::new(subject_pronouns) as Box<dyn Expr>,
Box::new(indefinite_pronouns),
]);
@@ -58,8 +58,8 @@ impl Default for ThingThink {
let adverb_of_frequency =
WordSet::new(&["always", "sometimes", "often", "usually", "never"]);
- let pre_context = FirstMatchOf::new(vec![
- Box::new(pronoun),
+ let pre_context = FirstMatchOf::new([
+ Box::new(pronoun) as Box<dyn Expr>,
Box::new(verb_to),
Box::new(modal),
Box::new(adverb_of_frequency),
diff --git a/harper-core/src/linting/update_place_names.rs b/harper-core/src/linting/update_place_names.rs
index f9fc132c4..d4432c2dc 100644
--- a/harper-core/src/linting/update_place_names.rs
+++ b/harper-core/src/linting/update_place_names.rs
@@ -79,8 +79,7 @@ impl<'a> Default for UpdatePlaceNames<'a> {
place_name_mappings
.iter()
.flat_map(|(_, old_names)| old_names.iter())
- .map(|old_name| Box::new(FixedPhrase::from_phrase(old_name)) as Box<dyn Expr>)
- .collect(),
+ .map(|old_name| Box::new(FixedPhrase::from_phrase(old_name)) as Box<dyn Expr>),
);
Self::new(expr, place_name_mappings)
diff --git a/harper-core/src/linting/web_scraping.rs b/harper-core/src/linting/web_scraping.rs
index aca119aaf..30de4babc 100644
--- a/harper-core/src/linting/web_scraping.rs
+++ b/harper-core/src/linting/web_scraping.rs
@@ -30,8 +30,8 @@ impl Default for WebScraping {
let hyphenated_compounds = FirstMatchOf::new(open_and_hyphenated_compounds);
- let web_scraps = FirstMatchOf::new(vec![
- Box::new(closed_compounds),
+ let web_scraps = FirstMatchOf::new([
+ Box::new(closed_compounds) as Box<dyn Expr>,
Box::new(hyphenated_compounds),
]);
@@ -71,7 +71,10 @@ impl Default for WebScraping {
.then_word_set(scrapables);
Self {
- expr: FirstMatchOf::new(vec![Box::new(web_scraps), Box::new(scrap_the_web)]),
+ expr: FirstMatchOf::new(vec![
+ Box::new(web_scraps) as Box<dyn Expr>,
+ Box::new(scrap_the_web),
+ ]),
}
}
}