Skip to content

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

refactor(core): `Pattern` -> `Expr` (#1393)

Elijah Pottera8fb0c6d6120
diff --git a/harper-core/src/document.rs b/harper-core/src/document.rs
index 519650a5a..efb5bc32b 100644
--- a/harper-core/src/document.rs
+++ b/harper-core/src/document.rs
@@ -4,10 +4,9 @@ use std::fmt::Display;
use paste::paste;
+use crate::expr::{Expr, ExprExt, LongestMatchOf, Repeating, SequenceExpr};
use crate::parsers::{Markdown, MarkdownOptions, Parser, PlainEnglish};
-use crate::patterns::{
- DocPattern, LongestMatchOf, Pattern, RepeatingPattern, SequencePattern, WordSet,
-};
+use crate::patterns::WordSet;
use crate::punctuation::Punctuation;
use crate::vec_ext::VecExt;
use crate::word_metadata::AdjectiveData;
@@ -157,9 +156,9 @@ impl Document {
self.articles_imply_not_verb();
}
- fn uncached_article_pattern() -> Lrc<SequencePattern> {
+ fn uncached_article_expr() -> Lrc<SequenceExpr> {
Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_determiner()
.then_whitespace()
.then(|t: &Token, _source: &[char]| t.kind.is_adjective() && t.kind.is_noun())
@@ -168,14 +167,14 @@ impl Document {
)
}
- thread_local! {static ARTICLE_PATTERN: Lrc<SequencePattern> = Document::uncached_article_pattern()}
+ thread_local! {static ARTICLE_EXPR: Lrc<SequenceExpr> = Document::uncached_article_expr()}
/// When a word that is either an adjective or a noun is sandwiched between an article and a noun,
/// it definitely is not a noun.
fn articles_imply_nouns(&mut self) {
- let pattern = Self::ARTICLE_PATTERN.with(|v| v.clone());
+ let expr = Self::ARTICLE_EXPR.with(|v| v.clone());
- for m in pattern.find_all_matches_in_doc(self) {
+ for m in expr.iter_matches_in_doc(self).collect::<Vec<_>>() {
if let TokenKind::Word(Some(metadata)) = &mut self.tokens[m.start + 2].kind {
metadata.noun = None;
metadata.verb = None;
@@ -186,9 +185,9 @@ impl Document {
/// A proposition-like word followed by a determiner or number is typically
/// really a preposition.
fn known_preposition(&mut self) {
- fn create_pattern() -> Lrc<SequencePattern> {
+ fn create_expr() -> Lrc<SequenceExpr> {
Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(WordSet::new(&["in", "at", "on", "to", "for", "by", "with"]))
.then_whitespace()
.then(|t: &Token, _source: &[char]| {
@@ -196,11 +195,11 @@ impl Document {
}),
)
}
- thread_local! {static PATTERN: Lrc<SequencePattern> = create_pattern()}
+ thread_local! {static EXPR: Lrc<SequenceExpr> = create_expr()}
- let pattern = PATTERN.with(|v| v.clone());
+ let expr = EXPR.with(|v| v.clone());
- for m in pattern.find_all_matches_in_doc(self) {
+ for m in expr.iter_matches_in_doc(self).collect::<Vec<_>>() {
if let TokenKind::Word(Some(metadata)) = &mut self.tokens[m.start].kind {
metadata.noun = None;
metadata.pronoun = None;
@@ -212,9 +211,9 @@ impl Document {
/// The first word after an article cannot be a verb.
fn articles_imply_not_verb(&mut self) {
- fn create_pattern() -> Lrc<SequencePattern> {
+ fn create_pattern() -> Lrc<SequenceExpr> {
Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(WordSet::new(&[
// articles
"a", "an", "the",
@@ -229,10 +228,10 @@ impl Document {
.then_verb(),
)
}
- thread_local! {static PATTERN: Lrc<SequencePattern> = create_pattern()}
- let pattern = PATTERN.with(|v| v.clone());
+ thread_local! {static EXPR: Lrc<SequenceExpr> = create_pattern()}
+ let expr = EXPR.with(|v| v.clone());
- for m in pattern.find_all_matches_in_doc(self) {
+ for m in expr.iter_matches_in_doc(self).collect::<Vec<_>>() {
if let TokenKind::Word(Some(metadata)) = &mut self.tokens[m.end - 1].kind {
if metadata.noun.is_none()
&& metadata.adjective.is_none()
@@ -478,18 +477,18 @@ impl Document {
}
thread_local! {
- static LATIN_PATTERN: Lrc<LongestMatchOf> = Document::uncached_latin_pattern();
+ static LATIN_EXPR: Lrc<LongestMatchOf> = Document::uncached_latin_expr();
}
- fn uncached_latin_pattern() -> Lrc<LongestMatchOf> {
+ fn uncached_latin_expr() -> Lrc<LongestMatchOf> {
Lrc::new(LongestMatchOf::new(vec![
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(WordSet::new(&["etc", "vs"]))
.then_period(),
),
Box::new(
- SequencePattern::aco("et")
+ SequenceExpr::aco("et")
.then_whitespace()
.t_aco("al")
.then_period(),
@@ -499,11 +498,11 @@ impl Document {
/// Assumes that the first matched token is the canonical one to be condensed into.
/// Takes a callback that can be used to retroactively edit the canonical token afterwards.
- fn condense_pattern<F>(&mut self, pattern: &impl Pattern, edit: F)
+ fn condense_expr<F>(&mut self, expr: &impl Expr, edit: F)
where
F: Fn(&mut Token),
{
- let matches = pattern.find_all_matches_in_doc(self);
+ let matches = expr.iter_matches_in_doc(self).collect::<Vec<_>>();
let mut remove_indices = VecDeque::with_capacity(matches.len());
@@ -517,7 +516,7 @@ impl Document {
}
fn condense_latin(&mut self) {
- self.condense_pattern(&Self::LATIN_PATTERN.with(|v| v.clone()), |_| {})
+ self.condense_expr(&Self::LATIN_EXPR.with(|v| v.clone()), |_| {})
}
/// Searches for multiple sequential newline tokens and condenses them down
@@ -606,25 +605,25 @@ impl Document {
self.tokens.remove_indices(to_remove);
}
- fn uncached_ellipsis_pattern() -> Lrc<RepeatingPattern> {
- let period = SequencePattern::default().then_period();
- Lrc::new(RepeatingPattern::new(Box::new(period), 2))
+ fn uncached_ellipsis_pattern() -> Lrc<Repeating> {
+ let period = SequenceExpr::default().then_period();
+ Lrc::new(Repeating::new(Box::new(period), 2))
}
thread_local! {
- static ELLIPSIS_PATTERN: Lrc<RepeatingPattern> = Document::uncached_ellipsis_pattern();
+ static ELLIPSIS_EXPR: Lrc<Repeating> = Document::uncached_ellipsis_pattern();
}
fn condense_ellipsis(&mut self) {
- let pattern = Self::ELLIPSIS_PATTERN.with(|v| v.clone());
- self.condense_pattern(&pattern, |tok| {
+ let expr = Self::ELLIPSIS_EXPR.with(|v| v.clone());
+ self.condense_expr(&expr, |tok| {
tok.kind = TokenKind::Punctuation(Punctuation::Ellipsis)
});
}
- fn uncached_contraction_pattern() -> Lrc<SequencePattern> {
+ fn uncached_contraction_expr() -> Lrc<SequenceExpr> {
Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_any_word()
.then_apostrophe()
.then_any_word(),
@@ -632,15 +631,15 @@ impl Document {
}
thread_local! {
- static CONTRACTION_PATTERN: Lrc<SequencePattern> = Document::uncached_contraction_pattern();
+ static CONTRACTION_EXPR: Lrc<SequenceExpr> = Document::uncached_contraction_expr();
}
/// Searches for contractions and condenses them down into single
/// tokens.
fn condense_contractions(&mut self) {
- let pattern = Self::CONTRACTION_PATTERN.with(|v| v.clone());
+ let expr = Self::CONTRACTION_EXPR.with(|v| v.clone());
- self.condense_pattern(&pattern, |_| {});
+ self.condense_expr(&expr, |_| {});
}
}
@@ -660,7 +659,7 @@ macro_rules! create_fns_on_doc {
self.tokens.[< last_ $thing _index >]()
}
- fn [<iter_ $thing _indices>](&self) -> impl Iterator<Item = usize> + '_ {
+ fn [<iter_ $thing _indices>](&self) -> impl DoubleEndedIterator<Item = usize> + '_ {
self.tokens.[< iter_ $thing _indices >]()
}
diff --git a/harper-core/src/expr/all.rs b/harper-core/src/expr/all.rs
new file mode 100644
index 000000000..f8bda662b
--- /dev/null
+++ b/harper-core/src/expr/all.rs
@@ -0,0 +1,40 @@
+use crate::{Span, Token, expr::Expr};
+
+/// A [`Step`] that consumes a list of expressions and only
+/// matches if all the child [`Expr`]s do.
+///
+/// It will return the position of the farthest window.
+#[derive(Default)]
+pub struct All {
+ children: Vec<Box<dyn Expr>>,
+}
+
+impl All {
+ pub fn new(children: Vec<Box<dyn Expr>>) -> Self {
+ Self { children }
+ }
+
+ pub fn add(&mut self, e: impl Expr + 'static) {
+ self.children.push(Box::new(e));
+ }
+}
+
+impl Expr for All {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ let mut longest: Option<Span> = None;
+
+ for expr in self.children.iter() {
+ let window = expr.run(cursor, tokens, source)?;
+
+ if let Some(longest_window) = longest {
+ if window.len() > longest_window.len() {
+ longest = Some(window);
+ }
+ } else {
+ longest = Some(window);
+ }
+ }
+
+ longest
+ }
+}
diff --git a/harper-core/src/expr/anchor_end.rs b/harper-core/src/expr/anchor_end.rs
new file mode 100644
index 000000000..3f63ee632
--- /dev/null
+++ b/harper-core/src/expr/anchor_end.rs
@@ -0,0 +1,51 @@
+use crate::Token;
+
+use super::Step;
+
+/// A [`Step`] which will match only if the cursor is over the last non-whitespace character in stream.
+/// It will return that token.
+///
+/// For example, if you built `SequenceExpr::default().t_aco("word").then(AnchorEnd)` and ran it on `This is a word`, the resulting `Span` would only cover the final word token.
+pub struct AnchorEnd;
+
+impl Step for AnchorEnd {
+ fn step(&self, tokens: &[Token], cursor: usize, _source: &[char]) -> Option<isize> {
+ if tokens
+ .iter()
+ .enumerate()
+ .rev()
+ .filter(|(_, t)| !t.kind.is_whitespace())
+ .map(|(i, _)| i)
+ .next()
+ == Some(cursor)
+ {
+ Some(0)
+ } else {
+ None
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::expr::ExprExt;
+ use crate::{Document, Span};
+
+ use super::AnchorEnd;
+
+ #[test]
+ fn matches_period() {
+ let document = Document::new_markdown_default_curated("This is a test.");
+ let matches: Vec<_> = AnchorEnd.iter_matches_in_doc(&document).collect();
+
+ assert_eq!(matches, vec![Span::new(7, 7)])
+ }
+
+ #[test]
+ fn does_not_match_empty() {
+ let document = Document::new_markdown_default_curated("");
+ let matches: Vec<_> = AnchorEnd.iter_matches_in_doc(&document).collect();
+
+ assert_eq!(matches, vec![])
+ }
+}
diff --git a/harper-core/src/expr/anchor_start.rs b/harper-core/src/expr/anchor_start.rs
new file mode 100644
index 000000000..c9f7e4535
--- /dev/null
+++ b/harper-core/src/expr/anchor_start.rs
@@ -0,0 +1,41 @@
+use crate::{Token, TokenStringExt};
+
+use super::Step;
+
+/// A [`Step`] which will match only if the cursor is over the first word-like of a token stream.
+/// It will return that token.
+pub struct AnchorStart;
+
+impl Step for AnchorStart {
+ fn step(&self, tokens: &[Token], cursor: usize, _source: &[char]) -> Option<isize> {
+ if tokens.iter_word_like_indices().next() == Some(cursor) {
+ Some(0)
+ } else {
+ None
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::expr::ExprExt;
+ use crate::{Document, Span};
+
+ use super::AnchorStart;
+
+ #[test]
+ fn matches_first_word() {
+ let document = Document::new_markdown_default_curated("This is a test.");
+ let matches: Vec<_> = AnchorStart.iter_matches_in_doc(&document).collect();
+
+ assert_eq!(matches, vec![Span::new(0, 0)])
+ }
+
+ #[test]
+ fn does_not_match_empty() {
+ let document = Document::new_markdown_default_curated("");
+ let matches: Vec<_> = AnchorStart.iter_matches_in_doc(&document).collect();
+
+ assert_eq!(matches, vec![])
+ }
+}
diff --git a/harper-core/src/patterns/pattern_map.rs b/harper-core/src/expr/expr_map.rs
similarity index 51%
rename from harper-core/src/patterns/pattern_map.rs
rename to harper-core/src/expr/expr_map.rs
index b4a654896..9bdf9db07 100644
--- a/harper-core/src/patterns/pattern_map.rs
+++ b/harper-core/src/expr/expr_map.rs
@@ -1,18 +1,19 @@
use crate::LSend;
+use crate::Span;
use crate::Token;
-use super::Pattern;
+use super::Expr;
-/// A map from [`Pattern`] to arbitrary data.
+/// A map from an [`Expr`] to arbitrary data.
///
-/// When used as a [`Pattern`] in and of itself, it simply iterates through
-/// all contained patterns, returning the first match found.
+/// When used as a [`Expr`] in and of itself, it simply iterates through
+/// all contained exprs, returning the first match found.
/// You should not assume this search is deterministic.
///
/// If you'd like to use this structure in a [`PatternLinter`](crate::linting::PatternLinter), you may want to provide
-/// the map as the search pattern, then use a pattern lookup once more to determine
+/// the map as the search expr, then use a pattern lookup once more to determine
/// the corresponding key.
-pub struct PatternMap<T>
+pub struct ExprMap<T>
where
T: LSend,
{
@@ -23,11 +24,11 @@ struct Row<T>
where
T: LSend,
{
- pub key: Box<dyn Pattern>,
+ pub key: Box<dyn Expr>,
pub element: T,
}
-impl<T> Default for PatternMap<T>
+impl<T> Default for ExprMap<T>
where
T: LSend,
{
@@ -38,21 +39,21 @@ where
}
}
-impl<T> PatternMap<T>
+impl<T> ExprMap<T>
where
T: LSend,
{
- pub fn insert(&mut self, pattern: impl Pattern + 'static, value: T) {
+ pub fn insert(&mut self, expr: impl Expr + 'static, value: T) {
self.rows.push(Row {
- key: Box::new(pattern),
+ key: Box::new(expr),
element: value,
});
}
/// Look up the corresponding value for the given map.
- pub fn lookup(&self, tokens: &[Token], source: &[char]) -> Option<&T> {
+ pub fn lookup(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<&T> {
for row in &self.rows {
- let len = row.key.matches(tokens, source);
+ let len = row.key.run(cursor, tokens, source);
if len.is_some() {
return Some(&row.element);
@@ -63,14 +64,14 @@ where
}
}
-impl<T> Pattern for PatternMap<T>
+impl<T> Expr for ExprMap<T>
where
T: LSend,
{
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
self.rows
.iter()
- .filter_map(|row| row.key.matches(tokens, source))
+ .filter_map(|row| row.key.run(cursor, tokens, source))
.next()
}
}
diff --git a/harper-core/src/expr/first_match_of.rs b/harper-core/src/expr/first_match_of.rs
new file mode 100644
index 000000000..9508b6343
--- /dev/null
+++ b/harper-core/src/expr/first_match_of.rs
@@ -0,0 +1,26 @@
+use super::Expr;
+use crate::{Span, Token};
+
+/// A naive expr collection that naively iterates through a list of patterns,
+/// returning the first one that matches.
+///
+/// Compare to [`LongestMatchOf`](super::LongestMatchOf), which returns the longest match.
+#[derive(Default)]
+pub struct FirstMatchOf {
+ exprs: Vec<Box<dyn Expr>>,
+}
+
+impl FirstMatchOf {
+ pub fn push(&mut self, expr: Box<dyn Expr>) {
+ self.exprs.push(expr);
+ }
+}
+
+impl Expr for FirstMatchOf {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ self.exprs
+ .iter()
+ .filter_map(|p| p.run(cursor, tokens, source))
+ .next()
+ }
+}
diff --git a/harper-core/src/patterns/fixed_phrase.rs b/harper-core/src/expr/fixed_phrase.rs
similarity index 67%
rename from harper-core/src/patterns/fixed_phrase.rs
rename to harper-core/src/expr/fixed_phrase.rs
index de9b70357..7cc417ed6 100644
--- a/harper-core/src/patterns/fixed_phrase.rs
+++ b/harper-core/src/expr/fixed_phrase.rs
@@ -1,6 +1,7 @@
+use crate::patterns::Word;
use crate::{Document, Token, TokenKind};
-use super::{Pattern, SequencePattern, Word};
+use super::{Expr, SequenceExpr};
/// Matches a fixed sequence of tokens as they appear in the input.
/// Case-insensitive for words but maintains exact matching for other token types.
@@ -8,15 +9,15 @@ use super::{Pattern, SequencePattern, Word};
/// # Example
///
/// ```rust
-/// use harper_core::patterns::{FixedPhrase, Pattern};
+/// use harper_core::expr::{FixedPhrase, Expr};
/// use harper_core::Document;
///
/// let doc = Document::new_plain_english_curated("Hello, world!");
/// let phrase = FixedPhrase::from_phrase("Hello, world!");
-/// assert!(phrase.matches(doc.get_tokens(), doc.get_source()).is_some());
+/// assert!(phrase.run(0, doc.get_tokens(), doc.get_source()).is_some());
/// ```
pub struct FixedPhrase {
- inner: SequencePattern,
+ inner: SequenceExpr,
}
impl FixedPhrase {
@@ -30,7 +31,7 @@ impl FixedPhrase {
/// Creates a [FixedPhrase] from a pre-tokenized document.
/// Allows custom tokenization by creating a `Document` first.
pub fn from_document(doc: &Document) -> Self {
- let mut phrase = SequencePattern::default();
+ let mut phrase = SequenceExpr::default();
for token in doc.fat_tokens() {
match token.kind {
@@ -60,20 +61,17 @@ impl FixedPhrase {
}
}
-impl Pattern for FixedPhrase {
- /// Matches this phrase against the start of the token slice.
- /// Returns `Some(len)` on match (number of tokens consumed), `None` otherwise.
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
- self.inner.matches(tokens, source)
+impl Expr for FixedPhrase {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<crate::Span> {
+ self.inner.run(cursor, tokens, source)
}
}
#[cfg(test)]
mod tests {
- use crate::{
- Document,
- patterns::{FixedPhrase, Pattern},
- };
+ use super::FixedPhrase;
+ use crate::expr::Expr;
+ use crate::{Document, Span};
#[test]
fn test_not_case_sensitive() {
@@ -82,28 +80,28 @@ mod tests {
let doc_title = Document::new_plain_english_curated("Hello World");
let phrase = FixedPhrase::from_document(&doc_lower);
assert_eq!(
- phrase.matches(doc_lower.get_tokens(), doc_title.get_source()),
- Some(3)
+ phrase.run(0, doc_lower.get_tokens(), doc_title.get_source()),
+ Some(Span::new(0, 3))
);
assert_eq!(
- phrase.matches(doc_lower.get_tokens(), doc_upper.get_source()),
- Some(3)
+ phrase.run(0, doc_lower.get_tokens(), doc_upper.get_source()),
+ Some(Span::new(0, 3))
);
assert_eq!(
- phrase.matches(doc_title.get_tokens(), doc_lower.get_source()),
- Some(3)
+ phrase.run(0, doc_title.get_tokens(), doc_lower.get_source()),
+ Some(Span::new(0, 3))
);
assert_eq!(
- phrase.matches(doc_title.get_tokens(), doc_upper.get_source()),
- Some(3)
+ phrase.run(0, doc_title.get_tokens(), doc_upper.get_source()),
+ Some(Span::new(0, 3))
);
assert_eq!(
- phrase.matches(doc_upper.get_tokens(), doc_lower.get_source()),
- Some(3)
+ phrase.run(0, doc_upper.get_tokens(), doc_lower.get_source()),
+ Some(Span::new(0, 3))
);
assert_eq!(
- phrase.matches(doc_upper.get_tokens(), doc_title.get_source()),
- Some(3)
+ phrase.run(0, doc_upper.get_tokens(), doc_title.get_source()),
+ Some(Span::new(0, 3))
);
}
}
diff --git a/harper-core/src/expr/longest_match_of.rs b/harper-core/src/expr/longest_match_of.rs
new file mode 100644
index 000000000..0b91a7942
--- /dev/null
+++ b/harper-core/src/expr/longest_match_of.rs
@@ -0,0 +1,39 @@
+use crate::{Span, Token, expr::Expr};
+
+/// A [`Step`] that returns the farthest offset of the longest match in a list of expressions.
+#[derive(Default)]
+pub struct LongestMatchOf {
+ exprs: Vec<Box<dyn Expr>>,
+}
+
+impl LongestMatchOf {
+ pub fn new(exprs: Vec<Box<dyn Expr>>) -> Self {
+ Self { exprs }
+ }
+
+ pub fn add(&mut self, expr: impl Expr + 'static) {
+ self.exprs.push(Box::new(expr));
+ }
+}
+
+impl Expr for LongestMatchOf {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ let mut longest: Option<Span> = None;
+
+ for expr in self.exprs.iter() {
+ let Some(window) = expr.run(cursor, tokens, source) else {
+ continue;
+ };
+
+ if let Some(longest_window) = longest {
+ if window.len() > longest_window.len() {
+ longest = Some(window);
+ }
+ } else {
+ longest = Some(window);
+ }
+ }
+
+ longest
+ }
+}
diff --git a/harper-core/src/patterns/mergeable_words.rs b/harper-core/src/expr/mergeable_words.rs
similarity index 77%
rename from harper-core/src/patterns/mergeable_words.rs
rename to harper-core/src/expr/mergeable_words.rs
index cb91f5e90..ff6e9b39e 100644
--- a/harper-core/src/patterns/mergeable_words.rs
+++ b/harper-core/src/expr/mergeable_words.rs
@@ -1,17 +1,18 @@
use std::sync::Arc;
-use crate::{CharString, Dictionary, FstDictionary, Token, WordMetadata};
+use crate::patterns::WhitespacePattern;
+use crate::{CharString, Dictionary, FstDictionary, Span, Token, WordMetadata};
-use super::{LongestMatchOf, Pattern, SequencePattern, WhitespacePattern};
+use super::{Expr, LongestMatchOf, SequenceExpr};
type PredicateFn = dyn Fn(Option<&WordMetadata>, Option<&WordMetadata>) -> bool + Send + Sync;
-/// A [`Pattern`] that identifies adjacent words that could potentially be merged into a single word.
+/// A [`Expr`] that identifies adjacent words that could potentially be merged into a single word.
///
/// This checks if two adjacent words could form a valid compound word, but first verifies
/// that the two words aren't already a valid lexeme in the dictionary (like "straight away").
pub struct MergeableWords {
- inner: SequencePattern,
+ inner: SequenceExpr,
dict: Arc<FstDictionary>,
predicate: Box<PredicateFn>,
}
@@ -21,7 +22,7 @@ impl MergeableWords {
predicate: impl Fn(Option<&WordMetadata>, Option<&WordMetadata>) -> bool + Send + Sync + 'static,
) -> Self {
Self {
- inner: SequencePattern::default()
+ inner: SequenceExpr::default()
.then_any_word()
.then(LongestMatchOf::new(vec![
Box::new(WhitespacePattern),
@@ -62,16 +63,16 @@ impl MergeableWords {
}
}
-impl Pattern for MergeableWords {
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
- let inner_match = self.inner.matches(tokens, source)?;
+impl Expr for MergeableWords {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ let inner_match = self.inner.run(cursor, tokens, source)?;
- if inner_match != 3 {
+ if inner_match.len() != 3 {
return None;
}
if self
- .get_merged_word(&tokens[0], &tokens[2], source)
+ .get_merged_word(&tokens[cursor], &tokens[cursor + 2], source)
.is_some()
{
return Some(inner_match);
@@ -83,20 +84,21 @@ impl Pattern for MergeableWords {
#[cfg(test)]
mod tests {
- use crate::{Document, WordMetadata, patterns::MergeableWords};
+ use super::MergeableWords;
+ use crate::{Document, WordMetadata};
fn predicate(meta_closed: Option<&WordMetadata>, meta_open: Option<&WordMetadata>) -> bool {
- meta_open.is_none() && meta_closed.map_or(false, |m| m.is_noun() && !m.is_proper_noun())
+ meta_open.is_none() && meta_closed.is_some_and(|m| m.is_noun() && !m.is_proper_noun())
}
#[test]
fn merges_open_compound_not_in_dict() {
// note book is not in the dictionary, but notebook is
let doc = Document::new_plain_english_curated("note book");
- let a = doc.tokens().nth(0).unwrap();
+ let a = doc.tokens().next().unwrap();
let b = doc.tokens().nth(2).unwrap();
- let merged = MergeableWords::new(predicate).get_merged_word(&a, &b, doc.get_source());
+ let merged = MergeableWords::new(predicate).get_merged_word(a, b, doc.get_source());
assert_eq!(merged, Some("notebook".chars().collect()));
}
@@ -105,10 +107,10 @@ mod tests {
fn does_not_merge_open_compound_in_dict() {
// straight away is in the dictionary, and straightaway is
let doc = Document::new_plain_english_curated("straight away");
- let a = doc.tokens().nth(0).unwrap();
+ let a = doc.tokens().next().unwrap();
let b = doc.tokens().nth(2).unwrap();
- let merged = MergeableWords::new(predicate).get_merged_word(&a, &b, doc.get_source());
+ let merged = MergeableWords::new(predicate).get_merged_word(a, b, doc.get_source());
assert_eq!(merged, None);
}
@@ -117,10 +119,10 @@ mod tests {
fn does_not_merge_invalid_compound() {
// neither quick for nor quickfox are in the dictionary
let doc = Document::new_plain_english_curated("quick fox");
- let a = doc.tokens().nth(0).unwrap();
+ let a = doc.tokens().next().unwrap();
let b = doc.tokens().nth(2).unwrap();
- let merged = MergeableWords::new(predicate).get_merged_word(&a, &b, doc.get_source());
+ let merged = MergeableWords::new(predicate).get_merged_word(a, b, doc.get_source());
assert_eq!(merged, None);
}
@@ -129,10 +131,10 @@ mod tests {
fn merges_open_compound() {
// Dictionary has "frontline" but not "front line"
let doc = Document::new_plain_english_curated("front line");
- let a = doc.tokens().nth(0).unwrap();
+ let a = doc.tokens().next().unwrap();
let b = doc.tokens().nth(2).unwrap();
- let merged = MergeableWords::new(predicate).get_merged_word(&a, &b, doc.get_source());
+ let merged = MergeableWords::new(predicate).get_merged_word(a, b, doc.get_source());
assert_eq!(merged, Some("frontline".chars().collect()));
}
@@ -141,10 +143,10 @@ mod tests {
fn merges_hyphenated_compound() {
// Doesn't check for "front-line" in the dictionary but matches it and "frontline" is in the dictionary
let doc = Document::new_plain_english_curated("front-line");
- let a = doc.tokens().nth(0).unwrap();
+ let a = doc.tokens().next().unwrap();
let b = doc.tokens().nth(2).unwrap();
- let merged = MergeableWords::new(predicate).get_merged_word(&a, &b, doc.get_source());
+ let merged = MergeableWords::new(predicate).get_merged_word(a, b, doc.get_source());
assert_eq!(merged, Some("frontline".chars().collect()));
}
diff --git a/harper-core/src/expr/mod.rs b/harper-core/src/expr/mod.rs
new file mode 100644
index 000000000..51da0ee59
--- /dev/null
+++ b/harper-core/src/expr/mod.rs
@@ -0,0 +1,143 @@
+mod all;
+mod anchor_end;
+mod anchor_start;
+mod expr_map;
+mod first_match_of;
+mod fixed_phrase;
+mod longest_match_of;
+mod mergeable_words;
+mod repeating;
+mod sequence_expr;
+mod similar_to_phrase;
+mod spelled_number_expr;
+mod step;
+mod time_unit_expr;
+mod unless_step;
+mod word_expr_group;
+
+#[cfg(not(feature = "concurrent"))]
+use std::rc::Rc;
+use std::sync::Arc;
+
+pub use all::All;
+pub use anchor_end::AnchorEnd;
+pub use anchor_start::AnchorStart;
+pub use expr_map::ExprMap;
+pub use fixed_phrase::FixedPhrase;
+pub use longest_match_of::LongestMatchOf;
+pub use mergeable_words::MergeableWords;
+pub use repeating::Repeating;
+pub use sequence_expr::SequenceExpr;
+pub use similar_to_phrase::SimilarToPhrase;
+pub use spelled_number_expr::SpelledNumberExpr;
+pub use step::Step;
+pub use time_unit_expr::TimeUnitExpr;
+pub use unless_step::UnlessStep;
+pub use word_expr_group::WordExprGroup;
+
+use crate::{Document, LSend, Span, Token};
+
+/// A common problem in Harper is that we need to identify tokens that fulfil certain criterion.
+/// An `Expr` is a way to express whether a certain set of tokens fulfil that criteria.
+/// When supplied a specific position in a token stream, the job of an `Expr` is to determine the window of tokens (including the cursor itself) that fulfils whatever criteria the author desires.
+/// It is then the job of another system to identify portions of documents that fulfil this criteria.
+pub trait Expr: LSend {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span>;
+}
+
+impl<S> Expr for S
+where
+ S: Step + ?Sized,
+{
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ self.step(tokens, cursor, source).map(|s| {
+ if s >= 0 {
+ Span::new_with_len(cursor, s as usize)
+ } else {
+ Span::new(add(cursor, s).unwrap(), cursor)
+ }
+ })
+ }
+}
+
+impl<E> Expr for Arc<E>
+where
+ E: Expr,
+{
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ self.as_ref().run(cursor, tokens, source)
+ }
+}
+
+#[cfg(not(feature = "concurrent"))]
+impl<E> Expr for Rc<E>
+where
+ E: Expr,
+{
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ self.as_ref().run(cursor, tokens, source)
+ }
+}
+
+fn add(u: usize, i: isize) -> Option<usize> {
+ if i.is_negative() {
+ u.checked_sub(i.wrapping_abs() as u32 as usize)
+ } else {
+ u.checked_add(i as usize)
+ }
+}
+
+pub trait ExprExt {
+ /// Iterate over all matches of this expression in the document, automatically filtering out
+ /// overlapping matches, preferring the first.
+ fn iter_matches<'a>(
+ &'a self,
+ tokens: &'a [Token],
+ source: &'a [char],
+ ) -> Box<dyn Iterator<Item = Span> + 'a>;
+
+ fn iter_matches_in_doc<'a>(&'a self, doc: &'a Document) -> Box<dyn Iterator<Item = Span> + 'a>;
+}
+
+impl<E: ?Sized> ExprExt for E
+where
+ E: Expr,
+{
+ fn iter_matches<'a>(
+ &'a self,
+ tokens: &'a [Token],
+ source: &'a [char],
+ ) -> Box<(dyn Iterator<Item = Span> + 'a)> {
+ let mut last_end = 0usize;
+
+ Box::new((0..tokens.len()).filter_map(move |i| {
+ let span = self.run(i, tokens, source)?;
+ if span.start >= last_end {
+ last_end = span.end;
+ Some(span)
+ } else {
+ None
+ }
+ }))
+ }
+
+ fn iter_matches_in_doc<'a>(
+ &'a self,
+ doc: &'a Document,
+ ) -> Box<(dyn Iterator<Item = Span> + 'a)> {
+ Box::new(self.iter_matches(doc.get_tokens(), doc.get_source()))
+ }
+}
+
+pub trait OwnedExprExt {
+ fn or(self, other: impl Expr + 'static) -> LongestMatchOf;
+}
+
+impl<E> OwnedExprExt for E
+where
+ E: Expr + 'static,
+{
+ fn or(self, other: impl Expr + 'static) -> LongestMatchOf {
+ LongestMatchOf::new(vec![Box::new(self), Box::new(other)])
+ }
+}
diff --git a/harper-core/src/expr/repeating.rs b/harper-core/src/expr/repeating.rs
new file mode 100644
index 000000000..2274291ed
--- /dev/null
+++ b/harper-core/src/expr/repeating.rs
@@ -0,0 +1,84 @@
+use super::Expr;
+use crate::{Span, Token};
+
+/// An expression that will match one or more repetitions of the same expression.
+///
+/// Somewhat reminiscent of the `+*` operator in Regex.
+pub struct Repeating {
+ inner: Box<dyn Expr>,
+ required_repetitions: usize,
+}
+
+impl Repeating {
+ pub fn new(expr: Box<dyn Expr>, required_repetitions: usize) -> Self {
+ Self {
+ inner: expr,
+ required_repetitions,
+ }
+ }
+}
+
+impl Expr for Repeating {
+ fn run(&self, mut cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ let mut window = Span::new_with_len(cursor, 0);
+ let mut repetition = 0;
+
+ loop {
+ let res = self.inner.run(cursor, tokens, source);
+
+ if let Some(res) = res {
+ window.expand_to_include(res.start);
+ window.expand_to_include(res.end - 1);
+
+ if res.start < cursor {
+ cursor = res.start;
+ } else {
+ cursor = res.end;
+ }
+
+ if res.is_empty() {
+ return Some(window);
+ }
+
+ repetition += 1;
+ } else if repetition >= self.required_repetitions {
+ return Some(window);
+ } else {
+ return None;
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+
+ use super::Repeating;
+ use crate::expr::{ExprExt, SequenceExpr};
+ use crate::patterns::AnyPattern;
+ use crate::{Document, Span};
+
+ #[test]
+ fn matches_anything() {
+ let doc = Document::new_plain_english_curated(
+ "This matcher will match the entirety of any document!",
+ );
+ let pat = Repeating::new(Box::new(SequenceExpr::from(AnyPattern)), 0);
+
+ assert_eq!(
+ pat.iter_matches(doc.get_tokens(), doc.get_source()).next(),
+ Some(Span::new(0, doc.get_tokens().len()))
+ )
+ }
+
+ #[test]
+ fn does_not_match_short() {
+ let doc = Document::new_plain_english_curated("No match");
+ let pat = Repeating::new(Box::new(SequenceExpr::from(AnyPattern)), 4);
+
+ assert_eq!(
+ pat.iter_matches(doc.get_tokens(), doc.get_source()).next(),
+ None
+ )
+ }
+}
diff --git a/harper-core/src/expr/sequence_expr.rs b/harper-core/src/expr/sequence_expr.rs
new file mode 100644
index 000000000..db0b76179
--- /dev/null
+++ b/harper-core/src/expr/sequence_expr.rs
@@ -0,0 +1,180 @@
+use paste::paste;
+
+use crate::{
+ Span, Token, TokenKind,
+ patterns::{AnyPattern, IndefiniteArticle, WhitespacePattern, Word},
+};
+
+use super::{Expr, Repeating, Step, UnlessStep};
+
+#[derive(Default)]
+pub struct SequenceExpr {
+ exprs: Vec<Box<dyn Expr>>,
+}
+
+/// Generate a `then_*` method from an available `is_*` function on [`TokenKind`].
+macro_rules! gen_then_from_is {
+ ($quality:ident) => {
+ paste! {
+ pub fn [< then_$quality >] (self) -> Self{
+ self.then(|tok: &Token, _source: &[char]| {
+ tok.kind.[< is_$quality >]()
+ })
+ }
+
+ pub fn [< then_one_or_more_$quality s >] (self) -> Self{
+ self.then_one_or_more(Box::new(|tok: &Token, _source: &[char]| {
+ tok.kind.[< is_$quality >]()
+ }))
+ }
+
+ pub fn [< then_anything_but_$quality >] (self) -> Self{
+ self.then(|tok: &Token, _source: &[char]| {
+ if tok.kind.[< is_$quality >](){
+ false
+ }else{
+ true
+ }
+ })
+ }
+ }
+ };
+}
+
+impl Expr for SequenceExpr {
+ /// Run the expression starting at an index, returning the total matched window.
+ ///
+ /// If any step returns `None`, the entire expression does as well.
+ fn run(&self, mut cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ let mut window = Span::new_with_len(cursor, 0);
+
+ for cur_expr in &self.exprs {
+ let out = cur_expr.run(cursor, tokens, source)?;
+
+ window.expand_to_include(out.start);
+ window.expand_to_include(out.end - 1);
+
+ if out.start < cursor {
+ cursor = out.start;
+ } else {
+ cursor = out.end;
+ }
+ }
+
+ Some(window)
+ }
+}
+
+impl SequenceExpr {
+ pub fn then(mut self, window: impl Expr + 'static) -> Self {
+ self.exprs.push(Box::new(window));
+ self
+ }
+
+ /// Appends the steps in `other` onto the end of `self`.
+ pub fn then_expr(mut self, mut other: Self) -> Self {
+ self.exprs.append(&mut other.exprs);
+ self
+ }
+
+ pub fn then_indefinite_article(self) -> Self {
+ self.then(IndefiniteArticle::default())
+ }
+
+ /// Match examples of `word` case-sensitively.
+ pub fn then_exact_word(self, word: &'static str) -> Self {
+ self.then(Word::new_exact(word))
+ }
+
+ /// Shorthand for [`Self::any_capitalization_of`].
+ pub fn aco(word: &'static str) -> Self {
+ Self::any_capitalization_of(word)
+ }
+
+ pub fn any_capitalization_of(word: &'static str) -> Self {
+ Self::default().then_any_capitalization_of(word)
+ }
+
+ /// Shorthand for [`Self::then_any_capitalization_of`].
+ pub fn t_aco(self, word: &'static str) -> Self {
+ self.then_any_capitalization_of(word)
+ }
+
+ /// Match examples of `word` that have any capitalization.
+ pub fn then_any_capitalization_of(self, word: &'static str) -> Self {
+ self.then(Word::new(word))
+ }
+
+ /// Matches any word.
+ pub fn then_any_word(self) -> Self {
+ self.then(|tok: &Token, _source: &[char]| tok.kind.is_word())
+ }
+
+ /// Matches any token whose `Kind` exactly matches.
+ pub fn then_strict(self, kind: TokenKind) -> Self {
+ self.then(move |tok: &Token, _source: &[char]| tok.kind == kind)
+ }
+
+ /// Shorthand for [`Self::then_whitespace`].
+ pub fn t_ws(self) -> Self {
+ self.then_whitespace()
+ }
+
+ /// Match against one or more whitespace tokens.
+ pub fn then_whitespace(self) -> Self {
+ self.then(WhitespacePattern)
+ }
+
+ pub fn then_one_or_more(self, expr: impl Expr + 'static) -> Self {
+ self.then(Repeating::new(Box::new(expr), 1))
+ }
+
+ /// Create a new condition that will step one token forward if met.
+ pub fn if_not_then_step_one(self, condition: impl Expr + 'static) -> Self {
+ self.then(UnlessStep::new(condition, |_tok: &Token, _src: &[char]| {
+ true
+ }))
+ }
+
+ pub fn t_any(self) -> Self {
+ self.then_anything()
+ }
+
+ pub fn then_anything(self) -> Self {
+ self.then(AnyPattern)
+ }
+
+ gen_then_from_is!(nominal);
+ gen_then_from_is!(noun);
+ gen_then_from_is!(possessive_nominal);
+ gen_then_from_is!(plural_nominal);
+ gen_then_from_is!(verb);
+ gen_then_from_is!(auxiliary_verb);
+ gen_then_from_is!(linking_verb);
+ gen_then_from_is!(pronoun);
+ gen_then_from_is!(punctuation);
+ gen_then_from_is!(conjunction);
+ gen_then_from_is!(comma);
+ gen_then_from_is!(period);
+ gen_then_from_is!(number);
+ gen_then_from_is!(case_separator);
+ gen_then_from_is!(adverb);
+ gen_then_from_is!(adjective);
+ gen_then_from_is!(apostrophe);
+ gen_then_from_is!(hyphen);
+ gen_then_from_is!(determiner);
+ gen_then_from_is!(proper_noun);
+ gen_then_from_is!(preposition);
+ gen_then_from_is!(not_plural_nominal);
+}
+
+impl<S> From<S> for SequenceExpr
+where
+ S: Step + 'static,
+{
+ fn from(step: S) -> Self {
+ Self {
+ exprs: vec![Box::new(step)],
+ }
+ }
+}
diff --git a/harper-core/src/patterns/similar_to_phrase.rs b/harper-core/src/expr/similar_to_phrase.rs
similarity index 69%
rename from harper-core/src/patterns/similar_to_phrase.rs
rename to harper-core/src/expr/similar_to_phrase.rs
index 729854f50..08f59edaa 100644
--- a/harper-core/src/patterns/similar_to_phrase.rs
+++ b/harper-core/src/expr/similar_to_phrase.rs
@@ -1,14 +1,15 @@
-use crate::{Document, Token, TokenKind};
+use crate::patterns::{WithinEditDistance, Word};
+use crate::{Document, Span, Token, TokenKind};
-use super::{Pattern, SequencePattern, Word, within_edit_distance::WithinEditDistance};
+use super::{Expr, SequenceExpr};
pub struct SimilarToPhrase {
- phrase: SequencePattern,
- fuzzy_phrase: SequencePattern,
+ phrase: SequenceExpr,
+ fuzzy_phrase: SequenceExpr,
}
impl SimilarToPhrase {
- /// Create an error-tolerant SequencePattern that looks for phrases similar to (but not the same as) that contained
+ /// Create an error-tolerant SequenceExpr that looks for phrases similar to (but not the same as) that contained
/// in the provided text.
///
/// This is an expensive operation, so try to only do it at startup and in tests.
@@ -20,15 +21,15 @@ impl SimilarToPhrase {
Self::from_doc(&document, max_edit_dist)
}
- /// Create an error-tolerant SequencePattern that looks for phrases similar to (but not the same as) that contained
+ /// Create an error-tolerant SequenceExpr that looks for phrases similar to (but not the same as) that contained
/// in the provided document.
///
/// This is an expensive operation, so try to only do it at startup and in tests.
///
/// It will panic if your document contains certain token types, so only run this with curated phrases.
pub fn from_doc(document: &Document, max_edit_dist: u8) -> Self {
- let mut phrase = SequencePattern::default();
- let mut fuzzy_phrase = SequencePattern::default();
+ let mut phrase = SequenceExpr::default();
+ let mut fuzzy_phrase = SequenceExpr::default();
for token in document.fat_tokens() {
match token.kind {
@@ -56,11 +57,11 @@ impl SimilarToPhrase {
}
}
-impl Pattern for SimilarToPhrase {
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
- if self.phrase.matches(tokens, source).is_some() {
+impl Expr for SimilarToPhrase {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ if self.phrase.run(cursor, tokens, source).is_some() {
return None;
}
- self.fuzzy_phrase.matches(tokens, source)
+ self.fuzzy_phrase.run(cursor, tokens, source)
}
}
diff --git a/harper-core/src/patterns/spelled_number_pattern.rs b/harper-core/src/expr/spelled_number_expr.rs
similarity index 74%
rename from harper-core/src/patterns/spelled_number_pattern.rs
rename to harper-core/src/expr/spelled_number_expr.rs
index aa2861df3..266e466c6 100644
--- a/harper-core/src/patterns/spelled_number_pattern.rs
+++ b/harper-core/src/expr/spelled_number_expr.rs
@@ -1,12 +1,15 @@
-use super::{LongestMatchOf, Pattern, SequencePattern, WhitespacePattern, WordSet};
-use crate::Token;
+use crate::expr::LongestMatchOf;
+use crate::patterns::{WhitespacePattern, WordSet};
+use crate::{Span, Token};
+
+use super::{Expr, SequenceExpr};
/// Matches spelled-out numbers from one to ninety-nine
#[derive(Default)]
-pub struct SpelledNumberPattern;
+pub struct SpelledNumberExpr;
-impl Pattern for SpelledNumberPattern {
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
+impl Expr for SpelledNumberExpr {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
if tokens.is_empty() {
return None;
}
@@ -48,7 +51,7 @@ impl Pattern for SpelledNumberPattern {
.collect::<Vec<&str>>(),
);
- let tens_units_compounds = SequencePattern::default()
+ let tens_units_compounds = SequenceExpr::default()
.then(WordSet::new(tens))
.then(LongestMatchOf::new(vec![
Box::new(|t: &Token, _s: &[char]| t.kind.is_hyphen()),
@@ -56,16 +59,17 @@ impl Pattern for SpelledNumberPattern {
]))
.then(WordSet::new(units));
- let pat = LongestMatchOf::new(vec![Box::new(single_words), Box::new(tens_units_compounds)]);
+ let expr =
+ LongestMatchOf::new(vec![Box::new(single_words), Box::new(tens_units_compounds)]);
- pat.matches(tokens, source)
+ expr.run(cursor, tokens, source)
}
}
#[cfg(test)]
mod tests {
- use super::super::DocPattern;
- use super::SpelledNumberPattern;
+ use super::SpelledNumberExpr;
+ use crate::expr::ExprExt;
use crate::{Document, Span};
trait SpanVecExt {
@@ -88,28 +92,30 @@ mod tests {
#[test]
fn matches_single_digit() {
let doc = Document::new_markdown_default_curated("one two three");
- let matches = SpelledNumberPattern.find_all_matches_in_doc(&doc);
- assert_eq!(matches.len(), 3);
+ let matches = SpelledNumberExpr.iter_matches_in_doc(&doc);
+ assert_eq!(matches.count(), 3);
}
#[test]
fn matches_teens() {
let doc = Document::new_markdown_default_curated("ten eleven twelve");
- let matches = SpelledNumberPattern.find_all_matches_in_doc(&doc);
- assert_eq!(matches.len(), 3);
+ let matches = SpelledNumberExpr.iter_matches_in_doc(&doc);
+ assert_eq!(matches.count(), 3);
}
#[test]
fn matches_tens() {
let doc = Document::new_markdown_default_curated("twenty thirty forty");
- let matches = SpelledNumberPattern.find_all_matches_in_doc(&doc);
- assert_eq!(matches.len(), 3);
+ let matches = SpelledNumberExpr.iter_matches_in_doc(&doc);
+ assert_eq!(matches.count(), 3);
}
#[test]
fn matches_compound_numbers() {
let doc = Document::new_markdown_default_curated("twenty-one thirty-two");
- let matches = SpelledNumberPattern.find_all_matches_in_doc(&doc);
+ let matches = SpelledNumberExpr
+ .iter_matches_in_doc(&doc)
+ .collect::<Vec<_>>();
// Debug output
println!("Found {} matches:", matches.len());
@@ -129,7 +135,9 @@ mod tests {
let doc = Document::new_markdown_default_curated(
"the answer to the ultimate question of life, the universe, and everything is forty-two",
);
- let matches = SpelledNumberPattern.find_all_matches_in_doc(&doc);
+ let matches = SpelledNumberExpr
+ .iter_matches_in_doc(&doc)
+ .collect::<Vec<_>>();
dbg!(&matches);
dbg!(matches.to_strings(&doc));
@@ -142,7 +150,9 @@ mod tests {
let doc = Document::new_markdown_default_curated(
"A, B, C It's easy as one, two, three. Or simple as Do-Re-Mi",
);
- let matches = SpelledNumberPattern.find_all_matches_in_doc(&doc);
+ let matches = SpelledNumberExpr
+ .iter_matches_in_doc(&doc)
+ .collect::<Vec<_>>();
assert_eq!(matches.to_strings(&doc), vec!["one", "two", "three"]);
}
@@ -150,7 +160,9 @@ mod tests {
#[test]
fn orwell() {
let doc = Document::new_markdown_default_curated("Nineteen Eighty-Four");
- let matches = SpelledNumberPattern.find_all_matches_in_doc(&doc);
+ let matches = SpelledNumberExpr
+ .iter_matches_in_doc(&doc)
+ .collect::<Vec<_>>();
assert_eq!(matches.to_strings(&doc), vec!["Nineteen", "Eighty-Four"]);
}
@@ -160,7 +172,9 @@ mod tests {
let doc = Document::new_markdown_default_curated(
"Maxwell Smart was Agent Eighty-Six, but who was Agent Ninety-Nine?",
);
- let matches = SpelledNumberPattern.find_all_matches_in_doc(&doc);
+ let matches = SpelledNumberExpr
+ .iter_matches_in_doc(&doc)
+ .collect::<Vec<_>>();
assert_eq!(matches.to_strings(&doc), vec!["Eighty-Six", "Ninety-Nine"]);
}
@@ -170,7 +184,9 @@ mod tests {
let doc = Document::new_markdown_default_curated(
"twenty-one, thirty two, forty-three, fifty four, sixty-five, seventy six, eighty-seven, ninety eight",
);
- let matches = SpelledNumberPattern.find_all_matches_in_doc(&doc);
+ let matches = SpelledNumberExpr
+ .iter_matches_in_doc(&doc)
+ .collect::<Vec<_>>();
assert_eq!(
matches.to_strings(&doc),
@@ -190,7 +206,9 @@ mod tests {
#[test]
fn waiting_since() {
let doc = Document::new_markdown_default_curated("I have been waiting since two hours.");
- let matches = SpelledNumberPattern.find_all_matches_in_doc(&doc);
+ let matches = SpelledNumberExpr
+ .iter_matches_in_doc(&doc)
+ .collect::<Vec<_>>();
assert_eq!(matches.to_strings(&doc), vec!["two"]);
}
diff --git a/harper-core/src/expr/step.rs b/harper-core/src/expr/step.rs
new file mode 100644
index 000000000..679cd9884
--- /dev/null
+++ b/harper-core/src/expr/step.rs
@@ -0,0 +1,19 @@
+use crate::{LSend, Token, patterns::Pattern};
+
+/// An atomic step within a larger expression.
+///
+/// Its principle job is to identify (if any) the next position of the cursor.
+/// When cursor is moved, all tokens between the current cursor and the target position will be
+/// added to the match group.
+pub trait Step: LSend {
+ fn step(&self, tokens: &[Token], cursor: usize, source: &[char]) -> Option<isize>;
+}
+
+impl<P> Step for P
+where
+ P: Pattern,
+{
+ fn step(&self, tokens: &[Token], cursor: usize, source: &[char]) -> Option<isize> {
+ self.matches(&tokens[cursor..], source).map(|i| i as isize)
+ }
+}
diff --git a/harper-core/src/patterns/time_unit_pattern.rs b/harper-core/src/expr/time_unit_expr.rs
similarity index 87%
rename from harper-core/src/patterns/time_unit_pattern.rs
rename to harper-core/src/expr/time_unit_expr.rs
index aaeb2c62d..2a941506b 100644
--- a/harper-core/src/patterns/time_unit_pattern.rs
+++ b/harper-core/src/expr/time_unit_expr.rs
@@ -1,6 +1,8 @@
-use crate::Token;
+use crate::expr::LongestMatchOf;
+use crate::patterns::WordSet;
+use crate::{Span, Token};
-use super::{LongestMatchOf, Pattern, WordSet};
+use super::Expr;
/// Matches a time unit.
///
@@ -10,10 +12,10 @@ use super::{LongestMatchOf, Pattern, WordSet};
/// Matches possessive forms (which are also common misspellings for the plurals).
/// Matches abbreviations.
#[derive(Default)]
-pub struct TimeUnitPattern;
+pub struct TimeUnitExpr;
-impl Pattern for TimeUnitPattern {
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
+impl Expr for TimeUnitExpr {
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
if tokens.is_empty() {
return None;
}
@@ -74,6 +76,6 @@ impl Pattern for TimeUnitPattern {
Box::new(units_other_apos),
]);
- units.matches(tokens, source)
+ units.run(cursor, tokens, source)
}
}
diff --git a/harper-core/src/expr/unless_step.rs b/harper-core/src/expr/unless_step.rs
new file mode 100644
index 000000000..fea4adda3
--- /dev/null
+++ b/harper-core/src/expr/unless_step.rs
@@ -0,0 +1,30 @@
+use crate::{Token, expr::Expr};
+
+use super::Step;
+
+/// Provides the ability to use an expression as a condition.
+/// If the condition does __not match__, it will return the result of the provided step.
+pub struct UnlessStep<E: Expr, S: Step> {
+ condition: E,
+ step: S,
+}
+
+impl<E, S> UnlessStep<E, S>
+where
+ E: Expr,
+ S: Step,
+{
+ pub fn new(condition: E, step: S) -> Self {
+ Self { condition, step }
+ }
+}
+
+impl<E: Expr, S: Step> Step for UnlessStep<E, S> {
+ fn step(&self, tokens: &[Token], cursor: usize, source: &[char]) -> Option<isize> {
+ if self.condition.run(cursor, tokens, source).is_none() {
+ self.step.step(tokens, cursor, source)
+ } else {
+ None
+ }
+ }
+}
diff --git a/harper-core/src/expr/word_expr_group.rs b/harper-core/src/expr/word_expr_group.rs
new file mode 100644
index 000000000..f220427c5
--- /dev/null
+++ b/harper-core/src/expr/word_expr_group.rs
@@ -0,0 +1,56 @@
+use hashbrown::HashMap;
+
+use super::first_match_of::FirstMatchOf;
+use super::{Expr, SequenceExpr};
+use crate::{CharString, Span, Token};
+
+/// An expression collection to look for expressions that start with a specific
+/// word.
+///
+/// The benefit of using this struct over other methods increases for larger collections.
+#[derive(Default)]
+pub struct WordExprGroup<E>
+where
+ E: Expr,
+{
+ exprs: HashMap<CharString, E>,
+}
+
+impl WordExprGroup<FirstMatchOf> {
+ pub fn add(&mut self, word: &str, expr: Box<dyn Expr>) {
+ let chars = word.chars().collect();
+
+ if let Some(group) = self.exprs.get_mut(&chars) {
+ group.push(expr);
+ } else {
+ let mut group = FirstMatchOf::default();
+ group.push(expr);
+ self.exprs.insert(chars, group);
+ }
+ }
+
+ /// Add a pattern that matches just a word on its own, without anything else required to match.
+ pub fn add_word(&mut self, word: &'static str) {
+ self.add(
+ word,
+ Box::new(SequenceExpr::default().then_exact_word(word)),
+ );
+ }
+}
+
+impl<E> Expr for WordExprGroup<E>
+where
+ E: Expr,
+{
+ fn run(&self, cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
+ let first = tokens.get(cursor)?;
+ if !first.kind.is_word() {
+ return None;
+ }
+
+ let word_chars = first.span.get_content(source);
+ let inner_pattern = self.exprs.get(word_chars)?;
+
+ inner_pattern.run(cursor, tokens, source)
+ }
+}
diff --git a/harper-core/src/lib.rs b/harper-core/src/lib.rs
index d6ab71f69..e425f694e 100644
--- a/harper-core/src/lib.rs
+++ b/harper-core/src/lib.rs
@@ -6,6 +6,7 @@ mod char_string;
mod currency;
mod document;
mod edit_distance;
+pub mod expr;
mod fat_token;
mod ignored_lints;
pub mod language_detection;
diff --git a/harper-core/src/linting/a_part.rs b/harper-core/src/linting/a_part.rs
index 6bc065b4e..7963ddbca 100644
--- a/harper-core/src/linting/a_part.rs
+++ b/harper-core/src/linting/a_part.rs
@@ -1,11 +1,13 @@
+use crate::expr::Expr;
+use crate::expr::FixedPhrase;
+use crate::expr::LongestMatchOf;
use crate::{
Token, TokenStringExt,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{FixedPhrase, LongestMatchOf, Pattern},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
};
pub struct APart {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for APart {
@@ -18,14 +20,14 @@ impl Default for APart {
]);
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for APart {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for APart {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/amounts_for.rs b/harper-core/src/linting/amounts_for.rs
index 2bb0d34b7..da0e66b51 100644
--- a/harper-core/src/linting/amounts_for.rs
+++ b/harper-core/src/linting/amounts_for.rs
@@ -1,19 +1,20 @@
-use crate::{
- Lrc, Token, TokenStringExt,
- patterns::{FixedPhrase, LongestMatchOf, Pattern, SequencePattern, WordSet},
-};
+use crate::expr::Expr;
+use crate::expr::FixedPhrase;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
+use crate::{Lrc, Token, TokenStringExt, patterns::WordSet};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct AmountsFor {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for AmountsFor {
fn default() -> Self {
let singular_context = WordSet::new(&["that", "which", "it", "this"]);
- let singular_pattern = SequencePattern::default()
+ let singular_pattern = SequenceExpr::default()
.then(singular_context)
.then_whitespace()
.then(Lrc::new(FixedPhrase::from_phrase("amounts for")));
@@ -22,13 +23,13 @@ impl Default for AmountsFor {
"they", "can", "could", "may", "might", "must", "should", "will", "would",
]);
- let plural_pattern = SequencePattern::default()
+ let plural_pattern = SequenceExpr::default()
.then(singular_context)
.then_whitespace()
.then(Lrc::new(FixedPhrase::from_phrase("amount for")));
Self {
- pattern: Box::new(LongestMatchOf::new(vec![
+ expr: Box::new(LongestMatchOf::new(vec![
Box::new(singular_pattern),
Box::new(plural_pattern),
])),
@@ -36,9 +37,9 @@ impl Default for AmountsFor {
}
}
-impl PatternLinter for AmountsFor {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for AmountsFor {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/ask_no_preposition.rs b/harper-core/src/linting/ask_no_preposition.rs
index dce4e6bd5..36788235d 100644
--- a/harper-core/src/linting/ask_no_preposition.rs
+++ b/harper-core/src/linting/ask_no_preposition.rs
@@ -1,11 +1,13 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::{
Span, Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{Pattern, SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::WordSet,
};
pub struct AskNoPreposition {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for AskNoPreposition {
@@ -16,7 +18,7 @@ impl Default for AskNoPreposition {
let objs = WordSet::new(&["me", "you", "him", "her", "it", "us", "them", "one"]);
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(verbs)
.then_whitespace()
.then_exact_word("to")
@@ -24,14 +26,14 @@ impl Default for AskNoPreposition {
.then(objs);
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for AskNoPreposition {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for AskNoPreposition {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/back_in_the_day.rs b/harper-core/src/linting/back_in_the_day.rs
index 46af73bfc..046b77a4d 100644
--- a/harper-core/src/linting/back_in_the_day.rs
+++ b/harper-core/src/linting/back_in_the_day.rs
@@ -1,12 +1,16 @@
+use crate::expr::Expr;
+use crate::expr::FixedPhrase;
+use crate::expr::OwnedExprExt;
+use crate::expr::SequenceExpr;
use crate::{
Lrc, Token, TokenStringExt,
- patterns::{FixedPhrase, OwnedPatternExt, Pattern, SequencePattern, WordSet},
+ patterns::{Pattern, WordSet},
};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct BackInTheDay {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
// The trailing words that should tell us to ignore the rule.
exceptions: Lrc<WordSet>,
}
@@ -16,22 +20,22 @@ impl Default for BackInTheDay {
let exceptions = Lrc::new(WordSet::new(&["before", "of", "when"]));
let phrase = Lrc::new(FixedPhrase::from_phrase("back in the days"));
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(phrase.clone())
.then_whitespace()
.then(exceptions.clone())
.or(phrase);
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
exceptions,
}
}
}
-impl PatternLinter for BackInTheDay {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for BackInTheDay {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/boring_words.rs b/harper-core/src/linting/boring_words.rs
index 2469e5e56..0aa3e1ffd 100644
--- a/harper-core/src/linting/boring_words.rs
+++ b/harper-core/src/linting/boring_words.rs
@@ -1,33 +1,31 @@
-use crate::{
- Token, TokenStringExt,
- patterns::{Pattern, WordPatternGroup},
-};
+use crate::expr::{Expr, WordExprGroup};
+use crate::{Token, TokenStringExt};
-use super::{Lint, LintKind, PatternLinter};
+use super::{ExprLinter, Lint, LintKind};
pub struct BoringWords {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for BoringWords {
fn default() -> Self {
- let mut pattern = WordPatternGroup::default();
+ let mut expr = WordExprGroup::default();
- pattern.add_word("very");
- pattern.add_word("interesting");
- pattern.add_word("several");
- pattern.add_word("most");
- pattern.add_word("many");
+ expr.add_word("very");
+ expr.add_word("interesting");
+ expr.add_word("several");
+ expr.add_word("most");
+ expr.add_word("many");
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(expr),
}
}
}
-impl PatternLinter for BoringWords {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for BoringWords {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/chock_full.rs b/harper-core/src/linting/chock_full.rs
index c6ac54cc4..28a65dd79 100644
--- a/harper-core/src/linting/chock_full.rs
+++ b/harper-core/src/linting/chock_full.rs
@@ -1,19 +1,22 @@
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
use crate::{
Token, TokenStringExt,
- patterns::{LongestMatchOf, Pattern, SequencePattern, WhitespacePattern, WordSet},
+ patterns::{WhitespacePattern, WordSet},
};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct ChockFull {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ChockFull {
fn default() -> Self {
Self {
- pattern: Box::new(
- SequencePattern::default()
+ expr: Box::new(
+ SequenceExpr::default()
.then(WordSet::new(&["chalk", "choke"]))
.then(LongestMatchOf::new(vec![
Box::new(WhitespacePattern),
@@ -25,9 +28,9 @@ impl Default for ChockFull {
}
}
-impl PatternLinter for ChockFull {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ChockFull {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_toks: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/compound_nouns/compound_noun_after_det_adj.rs b/harper-core/src/linting/compound_nouns/compound_noun_after_det_adj.rs
index a962f617c..46d6085f1 100644
--- a/harper-core/src/linting/compound_nouns/compound_noun_after_det_adj.rs
+++ b/harper-core/src/linting/compound_nouns/compound_noun_after_det_adj.rs
@@ -1,20 +1,17 @@
-use crate::{
- CharStringExt, TokenStringExt,
- linting::PatternLinter,
- patterns::{All, MergeableWords},
-};
+use crate::expr::All;
+use crate::expr::Expr;
+use crate::expr::MergeableWords;
+use crate::expr::SequenceExpr;
+use crate::{CharStringExt, TokenStringExt, linting::ExprLinter};
use super::{Lint, LintKind, Suggestion, is_content_word, predicate};
-use crate::{
- Lrc, Token,
- patterns::{Pattern, SequencePattern},
-};
+use crate::{Lrc, Token};
/// Two adjacent words separated by whitespace that if joined would be a valid noun.
pub struct CompoundNounAfterDetAdj {
- pattern: Box<dyn Pattern>,
- split_pattern: Lrc<MergeableWords>,
+ expr: Box<dyn Expr>,
+ split_expr: Lrc<MergeableWords>,
}
// This heuristic identifies potential compound nouns by:
@@ -24,7 +21,7 @@ pub struct CompoundNounAfterDetAdj {
// that is not also an adjective
impl Default for CompoundNounAfterDetAdj {
fn default() -> Self {
- let context_pattern = SequencePattern::default()
+ let context_expr = SequenceExpr::default()
.then(|tok: &Token, src: &[char]| {
let Some(Some(meta)) = tok.kind.as_word() else {
return false;
@@ -33,34 +30,34 @@ impl Default for CompoundNounAfterDetAdj {
|| (meta.is_adjective()
&& tok.span.get_content_string(src).to_lowercase() != "go")
})
- .then_whitespace()
+ .t_ws()
.then(is_content_word)
- .then_whitespace()
+ .t_ws()
.then(is_content_word);
- let split_pattern = Lrc::new(MergeableWords::new(|meta_closed, meta_open| {
+ let split_expr = Lrc::new(MergeableWords::new(|meta_closed, meta_open| {
predicate(meta_closed, meta_open)
}));
- let mut pattern = All::default();
- pattern.add(Box::new(context_pattern));
- pattern.add(Box::new(
- SequencePattern::default()
- .then_anything()
- .then_anything()
- .then(split_pattern.clone()),
- ));
+ let mut expr = All::default();
+ expr.add(context_expr);
+ expr.add(
+ SequenceExpr::default()
+ .t_any()
+ .t_any()
+ .then(split_expr.clone()),
+ );
Self {
- pattern: Box::new(pattern),
- split_pattern,
+ expr: Box::new(expr),
+ split_expr,
}
}
}
-impl PatternLinter for CompoundNounAfterDetAdj {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for CompoundNounAfterDetAdj {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
@@ -68,7 +65,7 @@ impl PatternLinter for CompoundNounAfterDetAdj {
let orig = span.get_content(source);
// If the pattern matched, this will not return `None`.
let word =
- self.split_pattern
+ self.split_expr
.get_merged_word(&matched_tokens[2], &matched_tokens[4], source)?;
Some(Lint {
diff --git a/harper-core/src/linting/compound_nouns/compound_noun_after_possessive.rs b/harper-core/src/linting/compound_nouns/compound_noun_after_possessive.rs
index 655ebe64b..4544032c8 100644
--- a/harper-core/src/linting/compound_nouns/compound_noun_after_possessive.rs
+++ b/harper-core/src/linting/compound_nouns/compound_noun_after_possessive.rs
@@ -1,15 +1,13 @@
-use crate::{
- CharStringExt, Lrc, TokenStringExt,
- linting::PatternLinter,
- patterns::{All, MergeableWords},
-};
+use crate::expr::All;
+use crate::expr::Expr;
+use crate::expr::MergeableWords;
+use crate::expr::SequenceExpr;
+use crate::patterns::AnyPattern;
+use crate::{CharStringExt, Lrc, TokenStringExt, linting::ExprLinter};
use super::{Lint, LintKind, Suggestion, is_content_word, predicate};
-use crate::{
- Token,
- patterns::{Pattern, SequencePattern},
-};
+use crate::Token;
/// Looks for closed compound nouns which can be condensed due to their position after a
/// possessive noun (which implies ownership).
@@ -19,13 +17,13 @@ use crate::{
/// harper-core/src/linting/lets_confusion/no_contraction_with_verb.rs
/// harper-core/src/linting/pronoun_contraction/should_contract.rs
pub struct CompoundNounAfterPossessive {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
split_pattern: Lrc<MergeableWords>,
}
impl Default for CompoundNounAfterPossessive {
fn default() -> Self {
- let context_pattern = SequencePattern::default()
+ let context_pattern = SequenceExpr::default()
.then_possessive_nominal()
.t_ws()
.then(is_content_word)
@@ -38,24 +36,24 @@ impl Default for CompoundNounAfterPossessive {
let mut pattern = All::default();
- pattern.add(Box::new(context_pattern));
- pattern.add(Box::new(
- SequencePattern::default()
- .then_anything()
- .then_anything()
+ pattern.add(context_pattern);
+ pattern.add(
+ SequenceExpr::default()
+ .then(AnyPattern)
+ .then(AnyPattern)
.then(split_pattern.clone()),
- ));
+ );
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
split_pattern,
}
}
}
-impl PatternLinter for CompoundNounAfterPossessive {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for CompoundNounAfterPossessive {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/compound_nouns/compound_noun_before_aux_verb.rs b/harper-core/src/linting/compound_nouns/compound_noun_before_aux_verb.rs
index bb6d557c8..07b0b4255 100644
--- a/harper-core/src/linting/compound_nouns/compound_noun_before_aux_verb.rs
+++ b/harper-core/src/linting/compound_nouns/compound_noun_before_aux_verb.rs
@@ -1,25 +1,23 @@
-use crate::{
- CharStringExt, Lrc, TokenStringExt,
- linting::PatternLinter,
- patterns::{All, MergeableWords},
-};
+use crate::expr::All;
+use crate::expr::Expr;
+use crate::expr::MergeableWords;
+use crate::expr::SequenceExpr;
+use crate::patterns::AnyPattern;
+use crate::{CharStringExt, Lrc, TokenStringExt, linting::ExprLinter};
use super::{Lint, LintKind, Suggestion, is_content_word, predicate};
-use crate::{
- Token,
- patterns::{Pattern, SequencePattern},
-};
+use crate::Token;
/// Two adjacent words separated by whitespace that if joined would be a valid noun.
pub struct CompoundNounBeforeAuxVerb {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
split_pattern: Lrc<MergeableWords>,
}
impl Default for CompoundNounBeforeAuxVerb {
fn default() -> Self {
- let context_pattern = SequencePattern::default()
+ let context_pattern = SequenceExpr::default()
.then(is_content_word)
.t_ws()
.then(is_content_word)
@@ -29,25 +27,25 @@ impl Default for CompoundNounBeforeAuxVerb {
predicate(meta_closed, meta_open)
}));
- let mut pattern = All::default();
- pattern.add(Box::new(context_pattern));
- pattern.add(Box::new(
- SequencePattern::default()
+ let mut expr = All::default();
+ expr.add(context_pattern);
+ expr.add(
+ SequenceExpr::default()
.then(split_pattern.clone())
- .then_anything()
- .then_anything(),
- ));
+ .then(AnyPattern)
+ .then(AnyPattern),
+ );
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(expr),
split_pattern,
}
}
}
-impl PatternLinter for CompoundNounBeforeAuxVerb {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for CompoundNounBeforeAuxVerb {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/confident.rs b/harper-core/src/linting/confident.rs
index c7e7a7681..a689104f0 100644
--- a/harper-core/src/linting/confident.rs
+++ b/harper-core/src/linting/confident.rs
@@ -1,33 +1,35 @@
-use crate::{
- Token,
- patterns::{OwnedPatternExt, Pattern, SequencePattern, Word},
-};
+use crate::expr::Expr;
+use crate::expr::OwnedExprExt;
+use crate::expr::SequenceExpr;
+use crate::{Token, patterns::Word};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct Confident {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for Confident {
fn default() -> Self {
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(
- (|tok: &Token, _source: &[char]| tok.kind.is_verb() || tok.kind.is_determiner())
- .or(Word::new("very")),
+ SequenceExpr::from(|tok: &Token, _source: &[char]| {
+ tok.kind.is_verb() || tok.kind.is_determiner()
+ })
+ .or(Word::new("very")),
)
.then_whitespace()
.t_aco("confidant");
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for Confident {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for Confident {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], _source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/dashes.rs b/harper-core/src/linting/dashes.rs
index 9d10ad122..960b02700 100644
--- a/harper-core/src/linting/dashes.rs
+++ b/harper-core/src/linting/dashes.rs
@@ -1,21 +1,21 @@
-use crate::{
- Token, TokenStringExt,
- patterns::{LongestMatchOf, Pattern, SequencePattern},
-};
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
+use crate::{Token, TokenStringExt};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
const EN_DASH: char = '–';
const EM_DASH: char = '—';
pub struct Dashes {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for Dashes {
fn default() -> Self {
- let en_dash = SequencePattern::default().then_hyphen().then_hyphen();
- let em_dash_or_longer = SequencePattern::default()
+ let en_dash = SequenceExpr::default().then_hyphen().then_hyphen();
+ let em_dash_or_longer = SequenceExpr::default()
.then_hyphen()
.then_hyphen()
.then_one_or_more_hyphens();
@@ -23,14 +23,14 @@ impl Default for Dashes {
let pattern = LongestMatchOf::new(vec![Box::new(em_dash_or_longer), Box::new(en_dash)]);
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for Dashes {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for Dashes {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], _source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/despite_of.rs b/harper-core/src/linting/despite_of.rs
index 90ed3d9f8..42fc22c54 100644
--- a/harper-core/src/linting/despite_of.rs
+++ b/harper-core/src/linting/despite_of.rs
@@ -1,29 +1,28 @@
-use crate::{
- Token, TokenStringExt,
- patterns::{Pattern, SequencePattern},
-};
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::{Token, TokenStringExt};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct DespiteOf {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for DespiteOf {
fn default() -> Self {
- let pattern = SequencePattern::aco("despite")
+ let pattern = SequenceExpr::aco("despite")
.then_whitespace()
.then_exact_word("of");
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for DespiteOf {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for DespiteOf {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/dot_initialisms.rs b/harper-core/src/linting/dot_initialisms.rs
index 4d46a4b40..8bd861bd0 100644
--- a/harper-core/src/linting/dot_initialisms.rs
+++ b/harper-core/src/linting/dot_initialisms.rs
@@ -1,24 +1,26 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::expr::WordExprGroup;
use hashbrown::HashMap;
-use super::{Lint, LintKind, PatternLinter, Suggestion};
-use crate::patterns::{Pattern, SequencePattern, WordPatternGroup};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
use crate::{Token, TokenStringExt};
pub struct DotInitialisms {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
corrections: HashMap<&'static str, &'static str>,
}
impl Default for DotInitialisms {
fn default() -> Self {
- let mut patterns = WordPatternGroup::default();
+ let mut patterns = WordExprGroup::default();
let mut corrections = HashMap::new();
corrections.insert("ie", "i.e.");
corrections.insert("eg", "e.g.");
for target in corrections.keys() {
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then_exact_word(target)
.then_punctuation();
@@ -26,15 +28,15 @@ impl Default for DotInitialisms {
}
Self {
- pattern: Box::new(patterns),
+ expr: Box::new(patterns),
corrections,
}
}
}
-impl PatternLinter for DotInitialisms {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for DotInitialisms {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/else_possessive.rs b/harper-core/src/linting/else_possessive.rs
index 8bc7f5c96..7087d24fe 100644
--- a/harper-core/src/linting/else_possessive.rs
+++ b/harper-core/src/linting/else_possessive.rs
@@ -1,11 +1,14 @@
+use crate::expr::Expr;
+use crate::expr::OwnedExprExt;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{OwnedPatternExt, Pattern, SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::WordSet,
};
pub struct ElsePossessive {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ElsePossessive {
@@ -19,22 +22,22 @@ impl Default for ElsePossessive {
"everyone",
"nobody",
])
- .or(SequencePattern::aco("no").then_whitespace().t_aco("one"));
+ .or(SequenceExpr::aco("no").then_whitespace().t_aco("one"));
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(pronouns)
.then_whitespace()
.t_aco("elses");
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for ElsePossessive {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ElsePossessive {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], _src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/everyday.rs b/harper-core/src/linting/everyday.rs
index 392be7a29..44be3ea0b 100644
--- a/harper-core/src/linting/everyday.rs
+++ b/harper-core/src/linting/everyday.rs
@@ -1,11 +1,12 @@
-use super::{Lint, LintKind, PatternLinter, Suggestion};
-use crate::{
- Lrc, Punctuation, Token, TokenKind, TokenStringExt,
- patterns::{All, LongestMatchOf, Pattern, SequencePattern, Word},
-};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
+use crate::expr::All;
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
+use crate::{Lrc, Punctuation, Token, TokenKind, TokenStringExt, patterns::Word};
pub struct Everyday {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
// TODO .is_present_tense_verb() is currently broken
@@ -31,30 +32,28 @@ fn is_unknown_word(tok: &Token) -> bool {
impl Default for Everyday {
fn default() -> Self {
let everyday = Word::new("everyday");
- let every_day = Lrc::new(
- SequencePattern::default()
- .t_aco("every")
- .t_ws()
- .t_aco("day"),
- );
-
- let everyday_bad_after = All::new(vec![
- Box::new(
- SequencePattern::default()
- .then(everyday.clone())
- .t_ws()
- .then_any_word(),
- ),
- Box::new(SequencePattern::default().t_any().t_any().then(
- |tok: &Token, src: &[char]| {
- !tok.kind.is_noun() && !is_unknown_word(tok) && !is_progressive_form(tok, src)
- },
- )),
- ]);
+ let every_day = Lrc::new(SequenceExpr::default().t_aco("every").t_ws().t_aco("day"));
+
+ let everyday_bad_after =
+ All::new(vec![
+ Box::new(
+ SequenceExpr::default()
+ .then(everyday.clone())
+ .t_ws()
+ .then_any_word(),
+ ),
+ Box::new(SequenceExpr::default().t_any().t_any().then(
+ |tok: &Token, src: &[char]| {
+ !tok.kind.is_noun()
+ && !is_unknown_word(tok)
+ && !is_progressive_form(tok, src)
+ },
+ )),
+ ]);
let bad_before_every_day = All::new(vec![
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_any_word()
.t_ws()
.then(every_day.clone()),
@@ -68,7 +67,7 @@ impl Default for Everyday {
// (why does) everyday feel the (same ?)
let everyday_ambiverb_after_then_noun = All::new(vec![
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(everyday.clone())
.t_ws()
.then_any_word()
@@ -76,7 +75,7 @@ impl Default for Everyday {
.then_any_word(),
),
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.t_any()
.t_any()
.then(|tok: &Token, _src: &[char]| tok.kind.is_noun() && tok.kind.is_verb())
@@ -88,12 +87,12 @@ impl Default for Everyday {
// (Do you actually improve if you draw) everyday?
let everyday_punctuation_after = All::new(vec![
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(everyday.clone())
.then_punctuation(),
),
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.t_any()
.then(|tok: &Token, _src: &[char]| {
matches!(
@@ -109,14 +108,14 @@ impl Default for Everyday {
// (However, the message goes far beyond) every day things.
let every_day_noun_after_then_punctuation = All::new(vec![
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(every_day.clone())
.t_ws()
.then_noun()
.then_punctuation(),
),
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.t_any()
.t_any()
.t_any()
@@ -156,7 +155,7 @@ impl Default for Everyday {
// verb, past form: "I coded every day" / "I learned everyday phrases"
Self {
- pattern: Box::new(LongestMatchOf::new(vec![
+ expr: Box::new(LongestMatchOf::new(vec![
Box::new(everyday_bad_after),
Box::new(bad_before_every_day),
Box::new(everyday_ambiverb_after_then_noun),
@@ -167,9 +166,9 @@ impl Default for Everyday {
}
}
-impl PatternLinter for Everyday {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for Everyday {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/expand_time_shorthands.rs b/harper-core/src/linting/expand_time_shorthands.rs
index 638668601..7051cc9ec 100644
--- a/harper-core/src/linting/expand_time_shorthands.rs
+++ b/harper-core/src/linting/expand_time_shorthands.rs
@@ -1,12 +1,15 @@
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
use std::sync::Arc;
-use super::{Lint, LintKind, PatternLinter};
+use super::{ExprLinter, Lint, LintKind};
use crate::Token;
use crate::linting::Suggestion;
-use crate::patterns::{ImpliesQuantity, LongestMatchOf, Pattern, SequencePattern, WordSet};
+use crate::patterns::{ImpliesQuantity, WordSet};
pub struct ExpandTimeShorthands {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl ExpandTimeShorthands {
@@ -16,16 +19,16 @@ impl ExpandTimeShorthands {
]));
Self {
- pattern: Box::new(SequencePattern::default().then(ImpliesQuantity).then(
+ expr: Box::new(SequenceExpr::default().then(ImpliesQuantity).then(
LongestMatchOf::new(vec![
- Box::new(SequencePattern::default().then(hotwords.clone())),
+ Box::new(SequenceExpr::default().then(hotwords.clone())),
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_whitespace()
.then(hotwords.clone()),
),
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_hyphen()
.then(hotwords.clone()),
),
@@ -56,9 +59,9 @@ impl Default for ExpandTimeShorthands {
}
}
-impl PatternLinter for ExpandTimeShorthands {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ExpandTimeShorthands {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/pattern_linter.rs b/harper-core/src/linting/expr_linter.rs
similarity index 69%
rename from harper-core/src/linting/pattern_linter.rs
rename to harper-core/src/linting/expr_linter.rs
index 49d7bd895..bbf0c4822 100644
--- a/harper-core/src/linting/pattern_linter.rs
+++ b/harper-core/src/linting/expr_linter.rs
@@ -1,21 +1,19 @@
+use crate::expr::{Expr, ExprExt};
use blanket::blanket;
-use crate::{
- Document, LSend, Token, TokenStringExt,
- patterns::{Pattern, PatternExt},
-};
+use crate::{Document, LSend, Token, TokenStringExt};
use super::{Lint, Linter};
-/// A trait that searches for [`Pattern`]s in [`Document`]s.
+/// A trait that searches for tokens that fulfil [`Expr`]s in a [`Document`].
///
/// Makes use of [`TokenStringExt::iter_chunks`] to avoid matching across sentence or clause
/// boundaries.
#[blanket(derive(Box))]
-pub trait PatternLinter: LSend {
+pub trait ExprLinter: LSend {
/// A simple getter for the pattern to be searched for.
- fn pattern(&self) -> &dyn Pattern;
- /// If any portions of a [`Document`] match [`Self::pattern`], they are passed through [`PatternLinter::match_to_lint`] to be
+ fn expr(&self) -> &dyn Expr;
+ /// If any portions of a [`Document`] match [`Self::expr`], they are passed through [`ExprLinter::match_to_lint`] to be
/// transformed into a [`Lint`] for editor consumption.
///
/// This function may return `None` to elect _not_ to produce a lint.
@@ -27,7 +25,7 @@ pub trait PatternLinter: LSend {
impl<L> Linter for L
where
- L: PatternLinter,
+ L: ExprLinter,
{
fn lint(&mut self, document: &Document) -> Vec<Lint> {
let mut lints = Vec::new();
@@ -45,13 +43,13 @@ where
}
}
-pub fn run_on_chunk(
- linter: &impl PatternLinter,
- chunk: &[Token],
- source: &[char],
-) -> impl Iterator<Item = Lint> {
+pub fn run_on_chunk<'a>(
+ linter: &'a impl ExprLinter,
+ chunk: &'a [Token],
+ source: &'a [char],
+) -> impl Iterator<Item = Lint> + 'a {
linter
- .pattern()
+ .expr()
.iter_matches(chunk, source)
.filter_map(|match_span| {
linter.match_to_lint(&chunk[match_span.start..match_span.end], source)
diff --git a/harper-core/src/linting/few_units_of_time_ago.rs b/harper-core/src/linting/few_units_of_time_ago.rs
index b1908044c..c163cf635 100644
--- a/harper-core/src/linting/few_units_of_time_ago.rs
+++ b/harper-core/src/linting/few_units_of_time_ago.rs
@@ -1,39 +1,32 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::expr::TimeUnitExpr;
use crate::{
Lrc, Token,
- linting::{Lint, PatternLinter, Suggestion},
- patterns::{FirstMatchOf, Pattern, SequencePattern, TimeUnitPattern},
+ linting::{ExprLinter, Lint, Suggestion},
};
pub struct FewUnitsOfTimeAgo {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for FewUnitsOfTimeAgo {
fn default() -> Self {
- let units = TimeUnitPattern;
-
- let mut start = FirstMatchOf::default();
- // start.push(Box::new(
- // SequencePattern::default()
- // .then_chunk_start()
- // .t_ws(),
- // ));
- // start.push(Box::new(SequencePattern::default().then_chunk_start()));
- start.push(Box::new(
- SequencePattern::default()
- .then(|tok: &Token, src: &[char]| {
- if tok.kind.is_word() {
- let chars = tok.span.get_content(src);
- chars != ['a'] && chars != ['A']
- } else {
- true
- }
- })
- .t_ws(),
- ));
-
- let pattern = Lrc::new(
- SequencePattern::default()
+ let units = TimeUnitExpr;
+
+ let start = SequenceExpr::default()
+ .then(|tok: &Token, src: &[char]| {
+ if tok.kind.is_word() {
+ let chars = tok.span.get_content(src);
+ chars != ['a'] && chars != ['A']
+ } else {
+ true
+ }
+ })
+ .t_ws();
+
+ let expr = Lrc::new(
+ SequenceExpr::default()
.then(start)
.t_aco("few")
.then_whitespace()
@@ -43,14 +36,14 @@ impl Default for FewUnitsOfTimeAgo {
);
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(expr),
}
}
}
-impl PatternLinter for FewUnitsOfTimeAgo {
- fn pattern(&self) -> &dyn crate::patterns::Pattern {
- self.pattern.as_ref()
+impl ExprLinter for FewUnitsOfTimeAgo {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/first_aid_kit.rs b/harper-core/src/linting/first_aid_kit.rs
index cf81bd797..8463938b3 100644
--- a/harper-core/src/linting/first_aid_kit.rs
+++ b/harper-core/src/linting/first_aid_kit.rs
@@ -1,29 +1,31 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::WordSet,
};
pub struct FirstAidKit {
- pattern: Box<dyn crate::patterns::Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for FirstAidKit {
fn default() -> Self {
let supply_words = WordSet::new(&["aid", "starter", "travel", "tool"]);
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(supply_words)
.then_whitespace()
.then_any_capitalization_of("kid");
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for FirstAidKit {
- fn pattern(&self) -> &dyn crate::patterns::Pattern {
- self.pattern.as_ref()
+impl ExprLinter for FirstAidKit {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/for_noun.rs b/harper-core/src/linting/for_noun.rs
index 92fbad9d3..665f1e6db 100644
--- a/harper-core/src/linting/for_noun.rs
+++ b/harper-core/src/linting/for_noun.rs
@@ -1,29 +1,32 @@
+use crate::expr::Expr;
+use crate::expr::OwnedExprExt;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- patterns::{NominalPhrase, OwnedPatternExt, Pattern, SequencePattern, Word},
+ patterns::{NominalPhrase, Word},
};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct ForNoun {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ForNoun {
fn default() -> Self {
- let pattern = SequencePattern::aco("fro")
+ let pattern = SequenceExpr::aco("fro")
.then_whitespace()
.then(NominalPhrase.or(Word::new("sure")));
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for ForNoun {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ForNoun {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/hedging.rs b/harper-core/src/linting/hedging.rs
index 6283147e4..a89276da6 100644
--- a/harper-core/src/linting/hedging.rs
+++ b/harper-core/src/linting/hedging.rs
@@ -1,29 +1,31 @@
-use crate::linting::{Lint, LintKind, PatternLinter};
-use crate::patterns::{FixedPhrase, LongestMatchOf, Pattern};
+use crate::expr::Expr;
+use crate::expr::FixedPhrase;
+use crate::expr::LongestMatchOf;
+use crate::linting::{ExprLinter, Lint, LintKind};
use crate::{Token, TokenStringExt};
/// A linter that detects hedging language.
pub struct Hedging {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for Hedging {
fn default() -> Self {
let phrases = vec!["I would argue that", ", so to speak", "to a certain degree"];
- let patterns: Vec<Box<dyn Pattern>> = phrases
+ let patterns: Vec<Box<dyn Expr>> = phrases
.into_iter()
- .map(|s| Box::new(FixedPhrase::from_phrase(s)) as Box<dyn Pattern>)
+ .map(|s| Box::new(FixedPhrase::from_phrase(s)) as Box<dyn Expr>)
.collect();
- let pattern = Box::new(LongestMatchOf::new(patterns));
- Self { pattern }
+ let expr = Box::new(LongestMatchOf::new(patterns));
+ Self { expr }
}
}
-impl PatternLinter for Hedging {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for Hedging {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], _source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/hereby.rs b/harper-core/src/linting/hereby.rs
index 9d486d658..305814517 100644
--- a/harper-core/src/linting/hereby.rs
+++ b/harper-core/src/linting/hereby.rs
@@ -1,31 +1,30 @@
-use crate::{
- Token, TokenStringExt,
- patterns::{Pattern, SequencePattern},
-};
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::{Token, TokenStringExt};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct Hereby {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for Hereby {
fn default() -> Self {
- let pattern = SequencePattern::aco("here")
+ let pattern = SequenceExpr::aco("here")
.then_whitespace()
.t_aco("by")
.then_whitespace()
.then_verb();
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for Hereby {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for Hereby {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/hop_hope/to_hop.rs b/harper-core/src/linting/hop_hope/to_hop.rs
index e97b69866..66360562d 100644
--- a/harper-core/src/linting/hop_hope/to_hop.rs
+++ b/harper-core/src/linting/hop_hope/to_hop.rs
@@ -1,16 +1,18 @@
-use super::super::{Lint, LintKind, PatternLinter};
+use super::super::{ExprLinter, Lint, LintKind};
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::linting::Suggestion;
-use crate::patterns::{Pattern, SequencePattern, WordSet};
+use crate::patterns::WordSet;
use crate::{CharString, CharStringExt};
use crate::{Token, char_string::char_string};
pub struct ToHop {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ToHop {
fn default() -> Self {
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(WordSet::new(&["hoping", "hoped", "hope"]))
.then_whitespace()
.t_aco("on")
@@ -20,7 +22,7 @@ impl Default for ToHop {
.then(WordSet::new(&["airplane", "plane", "bus", "call", "train"]));
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
@@ -36,9 +38,9 @@ impl ToHop {
}
}
-impl PatternLinter for ToHop {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ToHop {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/hop_hope/to_hope.rs b/harper-core/src/linting/hop_hope/to_hope.rs
index e8353b80f..c8652b219 100644
--- a/harper-core/src/linting/hop_hope/to_hope.rs
+++ b/harper-core/src/linting/hop_hope/to_hope.rs
@@ -1,15 +1,17 @@
-use super::super::{Lint, LintKind, PatternLinter};
+use super::super::{ExprLinter, Lint, LintKind};
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::linting::Suggestion;
-use crate::patterns::{Pattern, SequencePattern, WordSet};
+use crate::patterns::WordSet;
use crate::{Token, char_string::char_string};
pub struct ToHope {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ToHope {
fn default() -> Self {
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then_not_plural_nominal()
.then_whitespace()
.then(WordSet::new(&["hop", "hopped"]))
@@ -17,14 +19,14 @@ impl Default for ToHope {
.then_nominal();
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for ToHope {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ToHope {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/how_to.rs b/harper-core/src/linting/how_to.rs
index 61886ab65..807ef2439 100644
--- a/harper-core/src/linting/how_to.rs
+++ b/harper-core/src/linting/how_to.rs
@@ -1,24 +1,28 @@
+use crate::expr::All;
+use crate::expr::Expr;
+use crate::expr::OwnedExprExt;
+use crate::expr::SequenceExpr;
use crate::{
Token, TokenStringExt,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{All, InflectionOfBe, Invert, OwnedPatternExt, Pattern, SequencePattern},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::InflectionOfBe,
};
pub struct HowTo {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for HowTo {
fn default() -> Self {
let mut pattern = All::default();
- let pos_pattern = SequencePattern::default()
+ let pos_pattern = SequenceExpr::default()
.t_aco("how")
.then_whitespace()
.then_verb();
- pattern.add(Box::new(pos_pattern));
+ pattern.add(pos_pattern);
- let exceptions = SequencePattern::default()
+ let exceptions = SequenceExpr::default()
.then_anything()
.then_anything()
.then(
@@ -35,17 +39,17 @@ impl Default for HowTo {
})),
);
- pattern.add(Box::new(Invert::new(exceptions)));
+ pattern.add(SequenceExpr::default().if_not_then_step_one(exceptions));
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for HowTo {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for HowTo {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], _src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/hyphenate_number_day.rs b/harper-core/src/linting/hyphenate_number_day.rs
index 47338c4a5..88119672d 100644
--- a/harper-core/src/linting/hyphenate_number_day.rs
+++ b/harper-core/src/linting/hyphenate_number_day.rs
@@ -1,28 +1,28 @@
-use crate::{
- Token,
- patterns::{LongestMatchOf, NominalPhrase, Pattern, SequencePattern},
-};
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
+use crate::{Token, patterns::NominalPhrase};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct HyphenateNumberDay {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for HyphenateNumberDay {
fn default() -> Self {
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then_number()
.then_whitespace()
.t_aco("day")
.then(LongestMatchOf::new(vec![
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_whitespace()
.then(NominalPhrase),
),
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_hyphen()
.then_adjective()
.then_whitespace()
@@ -31,14 +31,14 @@ impl Default for HyphenateNumberDay {
]));
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for HyphenateNumberDay {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for HyphenateNumberDay {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], _source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/initialism_linter.rs b/harper-core/src/linting/initialism_linter.rs
index 034cbeeda..b29d7df59 100644
--- a/harper-core/src/linting/initialism_linter.rs
+++ b/harper-core/src/linting/initialism_linter.rs
@@ -1,16 +1,14 @@
+use crate::expr::Expr;
use itertools::Itertools;
-use crate::{
- Token,
- patterns::{Pattern, Word},
-};
+use crate::{Token, patterns::Word};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
/// A struct that can be composed to expand initialisms, respecting the capitalization of each
/// item.
pub struct InitialismLinter {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
/// The lowercase-normalized expansion of the initialism.
expansion_lower: Vec<Vec<char>>,
}
@@ -24,15 +22,15 @@ impl InitialismLinter {
.collect();
Self {
- pattern: Box::new(Word::from_char_string(initialism.chars().collect())),
+ expr: Box::new(Word::from_char_string(initialism.chars().collect())),
expansion_lower,
}
}
}
-impl PatternLinter for InitialismLinter {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for InitialismLinter {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
@@ -76,6 +74,4 @@ impl PatternLinter for InitialismLinter {
}
#[cfg(test)]
-mod tests {
- use super::InitialismLinter;
-}
+mod tests {}
diff --git a/harper-core/src/linting/initialisms.rs b/harper-core/src/linting/initialisms.rs
index ac1d9681b..685c321bc 100644
--- a/harper-core/src/linting/initialisms.rs
+++ b/harper-core/src/linting/initialisms.rs
@@ -8,7 +8,7 @@ pub fn lint_group() -> LintGroup {
macro_rules! add_initialism_mappings {
($group:expr, { $($name:expr => ($initialism:expr, $expanded:expr)),+ $(,)? }) => {
$(
- $group.add_pattern_linter(
+ $group.add_expr_linter(
$name,
Box::new(InitialismLinter::new($initialism, $expanded)),
);
diff --git a/harper-core/src/linting/it_is.rs b/harper-core/src/linting/it_is.rs
index 1e7328113..fc0cf8c90 100644
--- a/harper-core/src/linting/it_is.rs
+++ b/harper-core/src/linting/it_is.rs
@@ -1,11 +1,13 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{Pattern, SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::{Pattern, WordSet},
};
pub struct ItIs {
- pattern: Box<dyn crate::patterns::Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ItIs {
@@ -36,7 +38,7 @@ impl Default for ItIs {
"key",
"assault",
]);
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.t_aco("its")
.then_whitespace()
.then(move |tok: &Token, src: &[char]| {
@@ -55,14 +57,14 @@ impl Default for ItIs {
.then_whitespace()
.then_preposition();
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for ItIs {
- fn pattern(&self) -> &dyn crate::patterns::Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ItIs {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/it_would_be.rs b/harper-core/src/linting/it_would_be.rs
index d47966602..9808eff0b 100644
--- a/harper-core/src/linting/it_would_be.rs
+++ b/harper-core/src/linting/it_would_be.rs
@@ -1,11 +1,14 @@
+use crate::expr::Expr;
+use crate::expr::OwnedExprExt;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{OwnedPatternExt, Pattern, SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::WordSet,
};
pub struct ItWouldBe {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ItWouldBe {
@@ -29,7 +32,7 @@ impl Default for ItWouldBe {
]);
let branch = |has_not: bool, has_adj: bool| {
- let mut p = SequencePattern::default()
+ let mut p = SequenceExpr::default()
.then(head_verbs.clone())
.then_whitespace()
.t_aco("i") // the mistaken pronoun
@@ -55,14 +58,14 @@ impl Default for ItWouldBe {
.or(branch(true, true));
Self {
- pattern: Box::new(combined),
+ expr: Box::new(combined),
}
}
}
-impl PatternLinter for ItWouldBe {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ItWouldBe {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], _src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/its_contraction.rs b/harper-core/src/linting/its_contraction.rs
index 8e214c8d8..2229d9b7c 100644
--- a/harper-core/src/linting/its_contraction.rs
+++ b/harper-core/src/linting/its_contraction.rs
@@ -1,30 +1,32 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{Pattern, SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::WordSet,
};
pub struct ItsContraction {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ItsContraction {
fn default() -> Self {
let its = WordSet::new(&["its"]);
let verbs = WordSet::new(&["had", "been", "got"]);
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(its)
.then_whitespace()
.then(verbs);
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for ItsContraction {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ItsContraction {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/left_right_hand.rs b/harper-core/src/linting/left_right_hand.rs
index d4aaddde8..52ec805f2 100644
--- a/harper-core/src/linting/left_right_hand.rs
+++ b/harper-core/src/linting/left_right_hand.rs
@@ -1,17 +1,16 @@
-use crate::{
- Token,
- patterns::{Pattern, SequencePattern, WordSet},
-};
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::{Token, patterns::WordSet};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct LeftRightHand {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for LeftRightHand {
fn default() -> Self {
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(WordSet::new(&["left", "right"]))
.then_whitespace()
.t_aco("hand")
@@ -19,14 +18,14 @@ impl Default for LeftRightHand {
.then_noun();
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for LeftRightHand {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for LeftRightHand {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], _source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/lets_confusion/let_us_redundancy.rs b/harper-core/src/linting/lets_confusion/let_us_redundancy.rs
index 35dee917e..5b6157b2a 100644
--- a/harper-core/src/linting/lets_confusion/let_us_redundancy.rs
+++ b/harper-core/src/linting/lets_confusion/let_us_redundancy.rs
@@ -1,9 +1,8 @@
-use crate::{
- Token, TokenStringExt,
- patterns::{Pattern, SequencePattern},
-};
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::{Token, TokenStringExt};
-use crate::linting::{Lint, LintKind, PatternLinter, Suggestion};
+use crate::linting::{ExprLinter, Lint, LintKind, Suggestion};
/// See also:
/// harper-core/src/linting/compound_nouns/implied_ownership_compound_nouns.rs
@@ -11,24 +10,22 @@ use crate::linting::{Lint, LintKind, PatternLinter, Suggestion};
/// harper-core/src/linting/lets_confusion/no_contraction_with_verb.rs
/// harper-core/src/linting/pronoun_contraction/should_contract.rs
pub struct LetUsRedundancy {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for LetUsRedundancy {
fn default() -> Self {
- let pattern = SequencePattern::aco("let's")
- .then_whitespace()
- .then_pronoun();
+ let pattern = SequenceExpr::aco("let's").then_whitespace().then_pronoun();
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for LetUsRedundancy {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for LetUsRedundancy {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/lets_confusion/no_contraction_with_verb.rs b/harper-core/src/linting/lets_confusion/no_contraction_with_verb.rs
index bc12fcd33..ea4c66215 100644
--- a/harper-core/src/linting/lets_confusion/no_contraction_with_verb.rs
+++ b/harper-core/src/linting/lets_confusion/no_contraction_with_verb.rs
@@ -1,10 +1,13 @@
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
use crate::{
Token,
linting::{Lint, LintKind, Suggestion},
- patterns::{LongestMatchOf, Pattern, SequencePattern, WordSet},
+ patterns::WordSet,
};
-use crate::linting::PatternLinter;
+use crate::linting::ExprLinter;
/// See also:
/// harper-core/src/linting/compound_nouns/implied_ownership_compound_nouns.rs
@@ -12,18 +15,18 @@ use crate::linting::PatternLinter;
/// harper-core/src/linting/lets_confusion/let_us_redundancy.rs
/// harper-core/src/linting/pronoun_contraction/should_contract.rs
pub struct NoContractionWithVerb {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for NoContractionWithVerb {
fn default() -> Self {
// Only tests "let".
- let let_ws = SequencePattern::default()
+ let let_ws = SequenceExpr::default()
.then(WordSet::new(&["lets", "let"]))
.then_whitespace();
// Match verbs that are only verbs (not also nouns/adjectives) and not in -ing form
- let non_ing_verb = SequencePattern::default().then(|tok: &Token, _src: &[char]| {
+ let non_ing_verb = SequenceExpr::default().then(|tok: &Token, _src: &[char]| {
let Some(Some(meta)) = tok.kind.as_word() else {
return false;
};
@@ -35,7 +38,7 @@ impl Default for NoContractionWithVerb {
// Ambiguous word is a verb determined by heuristic of following word's part of speech
// Tests the next two words after "let".
- let verb_due_to_following_pos = SequencePattern::default()
+ let verb_due_to_following_pos = SequenceExpr::default()
.then(|tok: &Token, _source: &[char]| tok.kind.is_verb())
.then_whitespace()
.then(|tok: &Token, _source: &[char]| {
@@ -49,14 +52,14 @@ impl Default for NoContractionWithVerb {
]));
Self {
- pattern: Box::new(let_then_verb),
+ expr: Box::new(let_then_verb),
}
}
}
-impl PatternLinter for NoContractionWithVerb {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for NoContractionWithVerb {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/likewise.rs b/harper-core/src/linting/likewise.rs
index 0592e813a..309966328 100644
--- a/harper-core/src/linting/likewise.rs
+++ b/harper-core/src/linting/likewise.rs
@@ -1,38 +1,37 @@
-use crate::{
- Token, TokenStringExt,
- patterns::{All, Invert, Pattern, SequencePattern},
-};
+use crate::expr::All;
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::{Token, TokenStringExt};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct Likewise {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for Likewise {
fn default() -> Self {
- let mut pattern = All::default();
+ let mut expr = All::default();
- pattern.add(Box::new(
- SequencePattern::aco("like").then_whitespace().t_aco("wise"),
- ));
-
- pattern.add(Box::new(Invert::new(
- SequencePattern::default()
- .then_anything()
- .then_whitespace()
- .then_anything()
- .then_whitespace()
- .then_noun(),
- )));
+ expr.add(SequenceExpr::aco("like").then_whitespace().t_aco("wise"));
+ expr.add(
+ SequenceExpr::default().if_not_then_step_one(
+ SequenceExpr::default()
+ .then_anything()
+ .then_whitespace()
+ .then_anything()
+ .then_whitespace()
+ .then_noun(),
+ ),
+ );
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(expr),
}
}
}
-impl PatternLinter for Likewise {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for Likewise {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
let span = matched_tokens.span()?;
diff --git a/harper-core/src/linting/linking_verbs.rs b/harper-core/src/linting/linking_verbs.rs
deleted file mode 100644
index ca7e07b5f..000000000
--- a/harper-core/src/linting/linking_verbs.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-use super::{Lint, LintKind, Linter};
-use crate::CharStringExt;
-use crate::Document;
-use crate::TokenStringExt;
-
-/// Detect incorrect usage of linking verbs.
-///
-/// This ensures that linking verbs are preceded by a noun or pronoun.
-#[derive(Debug, Clone, Copy, Default)]
-pub struct LinkingVerbs;
-
-impl Linter for LinkingVerbs {
- fn lint(&mut self, document: &Document) -> Vec<Lint> {
- let mut output = Vec::new();
-
- for chunk in document.iter_chunks() {
- // The word prior to "is" must be a nominal (noun or pronoun).
- for idx in chunk.iter_linking_verb_indices() {
- let linking_verb = &chunk[idx];
- if let Some(prev_word) = &chunk[0..idx].last_word() {
- if let Some(metadata) = prev_word.kind.as_word().unwrap() {
- if !metadata.is_nominal() {
- let linking_verb_text = document.get_span_content(&linking_verb.span);
-
- output.push(Lint {
- span: linking_verb.span,
- lint_kind: LintKind::Miscellaneous,
- message: format!(
- "Linking verbs like “{}” must be preceded by a noun or pronoun.",
- linking_verb_text.to_string()
- ),
- ..Default::default()
- })
- }
- }
- }
- }
- }
-
- output
- }
-
- fn description(&self) -> &'static str {
- "Linking verbs connect nouns to other ideas. Make sure you do not accidentally link words that aren't nouns."
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::LinkingVerbs;
- use crate::linting::tests::assert_lint_count;
-
- #[test]
- fn dora() {
- assert_lint_count("Dora is a noun.", LinkingVerbs, 0);
- }
-
- #[test]
- fn working_wrong() {
- assert_lint_count("working is not a noun.", LinkingVerbs, 1);
- }
-
- #[test]
- fn working_right() {
- assert_lint_count("\"working\" is a noun.", LinkingVerbs, 0);
- }
-}
diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rs
index 1dfe9c61d..f09e78c9e 100644
--- a/harper-core/src/linting/lint_group.rs
+++ b/harper-core/src/linting/lint_group.rs
@@ -31,6 +31,7 @@ use super::ellipsis_length::EllipsisLength;
use super::else_possessive::ElsePossessive;
use super::everyday::Everyday;
use super::expand_time_shorthands::ExpandTimeShorthands;
+use super::expr_linter::run_on_chunk;
use super::few_units_of_time_ago::FewUnitsOfTimeAgo;
use super::first_aid_kit::FirstAidKit;
use super::for_noun::ForNoun;
@@ -44,7 +45,6 @@ use super::its_contraction::ItsContraction;
use super::left_right_hand::LeftRightHand;
use super::lets_confusion::LetsConfusion;
use super::likewise::Likewise;
-use super::linking_verbs::LinkingVerbs;
use super::long_sentences::LongSentences;
use super::merge_words::MergeWords;
use super::modal_of::ModalOf;
@@ -60,7 +60,6 @@ use super::one_and_the_same::OneAndTheSame;
use super::open_the_light::OpenTheLight;
use super::out_of_date::OutOfDate;
use super::oxymorons::Oxymorons;
-use super::pattern_linter::run_on_chunk;
use super::phrasal_verb_as_compound_noun::PhrasalVerbAsCompoundNoun;
use super::pique_interest::PiqueInterest;
use super::possessive_your::PossessiveYour;
@@ -88,7 +87,7 @@ use super::widely_accepted::WidelyAccepted;
use super::win_prize::WinPrize;
use super::wordpress_dotcom::WordPressDotcom;
use super::{CurrencyPlacement, HtmlDescriptionLinter, Linter, NoOxfordComma, OxfordComma};
-use super::{Lint, PatternLinter};
+use super::{ExprLinter, Lint};
use crate::linting::dashes::Dashes;
use crate::linting::open_compounds::OpenCompounds;
use crate::linting::{closed_compounds, initialisms, phrase_corrections};
@@ -191,14 +190,14 @@ pub struct LintGroup {
/// We use a binary map here so the ordering is stable.
linters: BTreeMap<String, Box<dyn Linter>>,
/// We use a binary map here so the ordering is stable.
- pattern_linters: BTreeMap<String, Box<dyn PatternLinter>>,
- /// Since [`PatternLinter`]s operate on a chunk-basis, we can store a
+ expr_linters: BTreeMap<String, Box<dyn ExprLinter>>,
+ /// Since [`ExprLinter`]s operate on a chunk-basis, we can store a
/// mapping of `Chunk -> Lint` and only re-run the pattern linters
/// when a chunk changes.
///
/// Since the pattern linter results also depend on the config, we hash it and pass it as part
/// of the key.
- chunk_pattern_cache: LruCache<(CharString, u64), Vec<Lint>>,
+ chunk_expr_cache: LruCache<(CharString, u64), Vec<Lint>>,
hasher_builder: RandomState,
}
@@ -207,15 +206,15 @@ impl LintGroup {
Self {
config: LintGroupConfig::default(),
linters: BTreeMap::new(),
- pattern_linters: BTreeMap::new(),
- chunk_pattern_cache: LruCache::new(NonZero::new(10000).unwrap()),
+ expr_linters: BTreeMap::new(),
+ chunk_expr_cache: LruCache::new(NonZero::new(10000).unwrap()),
hasher_builder: RandomState::default(),
}
}
/// Check if the group already contains a linter with a given name.
pub fn contains_key(&self, name: impl AsRef<str>) -> bool {
- self.linters.contains_key(name.as_ref()) || self.pattern_linters.contains_key(name.as_ref())
+ self.linters.contains_key(name.as_ref()) || self.expr_linters.contains_key(name.as_ref())
}
/// Add a [`Linter`] to the group, returning whether the operation was successful.
@@ -230,20 +229,20 @@ impl LintGroup {
}
}
- /// Add a [`PatternLinter`] to the group, returning whether the operation was successful.
+ /// Add a [`ExprLinter`] 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.
///
/// This function is not significantly different from [`Self::add`], but allows us to take
- /// advantage of some properties of [`PatternLinter`]s for cache optimization.
- pub fn add_pattern_linter(
+ /// advantage of some properties of [`ExprLinter`]s for cache optimization.
+ pub fn add_expr_linter(
&mut self,
name: impl AsRef<str>,
- linter: impl PatternLinter + 'static,
+ linter: impl ExprLinter + 'static,
) -> bool {
if self.contains_key(&name) {
false
} else {
- self.pattern_linters
+ self.expr_linters
.insert(name.as_ref().to_string(), Box::new(linter));
true
}
@@ -257,14 +256,14 @@ impl LintGroup {
let other_linters = std::mem::take(&mut other.linters);
self.linters.extend(other_linters);
- let other_pattern_linters = std::mem::take(&mut other.pattern_linters);
- self.pattern_linters.extend(other_pattern_linters);
+ let other_pattern_linters = std::mem::take(&mut other.expr_linters);
+ self.expr_linters.extend(other_pattern_linters);
}
pub fn iter_keys(&self) -> impl Iterator<Item = &str> {
self.linters
.keys()
- .chain(self.pattern_linters.keys())
+ .chain(self.expr_linters.keys())
.map(|v| v.as_str())
}
@@ -287,9 +286,9 @@ impl LintGroup {
.iter()
.map(|(key, value)| (key.as_str(), value.description()))
.chain(
- self.pattern_linters
+ self.expr_linters
.iter()
- .map(|(key, value)| (key.as_str(), PatternLinter::description(value))),
+ .map(|(key, value)| (key.as_str(), ExprLinter::description(value))),
)
.collect()
}
@@ -300,7 +299,7 @@ impl LintGroup {
.iter()
.map(|(key, value)| (key.as_str(), value.description_html()))
.chain(
- self.pattern_linters
+ self.expr_linters
.iter()
.map(|(key, value)| (key.as_str(), value.description_html())),
)
@@ -326,7 +325,7 @@ impl LintGroup {
macro_rules! insert_pattern_rule {
($rule:ident, $default_config:expr) => {
- out.add_pattern_linter(stringify!($rule), $rule::default());
+ out.add_expr_linter(stringify!($rule), $rule::default());
out.config
.set_rule_enabled(stringify!($rule), $default_config);
};
@@ -375,7 +374,6 @@ impl LintGroup {
insert_pattern_rule!(LeftRightHand, true);
insert_struct_rule!(LetsConfusion, true);
insert_pattern_rule!(Likewise, true);
- insert_struct_rule!(LinkingVerbs, false);
insert_struct_rule!(LongSentences, true);
insert_struct_rule!(MergeWords, true);
insert_pattern_rule!(ModalOf, true);
@@ -474,12 +472,12 @@ impl Linter for LintGroup {
let config_hash = self.hasher_builder.hash_one(&self.config);
let key = (chunk_chars.into(), config_hash);
- let mut chunk_results = if let Some(hit) = self.chunk_pattern_cache.get(&key) {
+ let mut chunk_results = if let Some(hit) = self.chunk_expr_cache.get(&key) {
hit.clone()
} else {
let mut pattern_lints = Vec::new();
- for (key, linter) in &mut self.pattern_linters {
+ for (key, linter) in &mut self.expr_linters {
if self.config.is_rule_enabled(key) {
pattern_lints.extend(run_on_chunk(linter, chunk, document.get_source()));
}
@@ -490,7 +488,7 @@ impl Linter for LintGroup {
lint.span.pull_by(chunk_span.start);
}
- self.chunk_pattern_cache.put(key, pattern_lints.clone());
+ self.chunk_expr_cache.put(key, pattern_lints.clone());
pattern_lints
};
diff --git a/harper-core/src/linting/map_phrase_linter.rs b/harper-core/src/linting/map_phrase_linter.rs
index 3690753c3..1cb3e6de7 100644
--- a/harper-core/src/linting/map_phrase_linter.rs
+++ b/harper-core/src/linting/map_phrase_linter.rs
@@ -1,25 +1,28 @@
-use super::{Lint, LintKind, PatternLinter};
+use super::{ExprLinter, Lint, LintKind};
+use crate::expr::Expr;
+use crate::expr::FixedPhrase;
+use crate::expr::LongestMatchOf;
+use crate::expr::SimilarToPhrase;
use crate::linting::Suggestion;
-use crate::patterns::{FixedPhrase, LongestMatchOf, Pattern, SimilarToPhrase};
use crate::{Token, TokenStringExt};
pub struct MapPhraseLinter {
description: String,
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
correct_forms: Vec<String>,
message: String,
}
impl MapPhraseLinter {
pub fn new(
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
correct_forms: impl IntoIterator<Item = impl ToString>,
message: impl ToString,
description: impl ToString,
) -> Self {
Self {
description: description.to_string(),
- pattern,
+ expr,
correct_forms: correct_forms.into_iter().map(|f| f.to_string()).collect(),
message: message.to_string(),
}
@@ -44,8 +47,8 @@ impl MapPhraseLinter {
phrase
.into_iter()
.map(|p| {
- let pattern: Box<dyn Pattern> = Box::new(FixedPhrase::from_phrase(p.as_ref()));
- pattern
+ let expr: Box<dyn Expr> = Box::new(FixedPhrase::from_phrase(p.as_ref()));
+ expr
})
.collect(),
);
@@ -82,9 +85,9 @@ impl MapPhraseLinter {
}
}
-impl PatternLinter for MapPhraseLinter {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for MapPhraseLinter {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rs
index eafa1bbc2..d35e442b5 100644
--- a/harper-core/src/linting/mod.rs
+++ b/harper-core/src/linting/mod.rs
@@ -25,6 +25,7 @@ mod ellipsis_length;
mod else_possessive;
mod everyday;
mod expand_time_shorthands;
+mod expr_linter;
mod few_units_of_time_ago;
mod first_aid_kit;
mod for_noun;
@@ -42,7 +43,6 @@ mod its_contraction;
mod left_right_hand;
mod lets_confusion;
mod likewise;
-mod linking_verbs;
mod lint;
mod lint_group;
mod lint_kind;
@@ -66,7 +66,6 @@ mod open_the_light;
mod out_of_date;
mod oxford_comma;
mod oxymorons;
-mod pattern_linter;
mod phrasal_verb_as_compound_noun;
mod phrase_corrections;
mod pique_interest;
@@ -117,6 +116,7 @@ pub use dot_initialisms::DotInitialisms;
pub use ellipsis_length::EllipsisLength;
pub use everyday::Everyday;
pub use expand_time_shorthands::ExpandTimeShorthands;
+pub use expr_linter::ExprLinter;
pub use few_units_of_time_ago::FewUnitsOfTimeAgo;
pub use for_noun::ForNoun;
pub use hedging::Hedging;
@@ -130,7 +130,6 @@ pub use its_contraction::ItsContraction;
pub use left_right_hand::LeftRightHand;
pub use lets_confusion::LetsConfusion;
pub use likewise::Likewise;
-pub use linking_verbs::LinkingVerbs;
pub use lint::Lint;
pub use lint_group::{LintGroup, LintGroupConfig};
pub use lint_kind::LintKind;
@@ -151,7 +150,6 @@ pub use open_the_light::OpenTheLight;
pub use out_of_date::OutOfDate;
pub use oxford_comma::OxfordComma;
pub use oxymorons::Oxymorons;
-pub use pattern_linter::PatternLinter;
pub use phrasal_verb_as_compound_noun::PhrasalVerbAsCompoundNoun;
pub use pique_interest::PiqueInterest;
pub use possessive_your::PossessiveYour;
diff --git a/harper-core/src/linting/modal_of.rs b/harper-core/src/linting/modal_of.rs
index a1f450a21..89ec75df0 100644
--- a/harper-core/src/linting/modal_of.rs
+++ b/harper-core/src/linting/modal_of.rs
@@ -1,12 +1,12 @@
-use crate::{
- Lrc, Token, TokenStringExt,
- patterns::{LongestMatchOf, Pattern, SequencePattern, WordSet},
-};
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
+use crate::{Lrc, Token, TokenStringExt, patterns::WordSet};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct ModalOf {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ModalOf {
@@ -22,22 +22,22 @@ impl Default for ModalOf {
});
let modal_of = Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(words)
.then_whitespace()
.t_aco("of"),
);
- let ws_course = Lrc::new(SequencePattern::default().then_whitespace().t_aco("course"));
+ let ws_course = Lrc::new(SequenceExpr::default().then_whitespace().t_aco("course"));
let modal_of_course = Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(modal_of.clone())
.then(ws_course.clone()),
);
let anyword_might_of = Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_any_word()
.then_whitespace()
.t_aco("might")
@@ -46,13 +46,13 @@ impl Default for ModalOf {
);
let anyword_might_of_course = Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(anyword_might_of.clone())
.then(ws_course.clone()),
);
Self {
- pattern: Box::new(LongestMatchOf::new(vec![
+ expr: Box::new(LongestMatchOf::new(vec![
Box::new(anyword_might_of_course),
Box::new(modal_of_course),
Box::new(anyword_might_of),
@@ -62,9 +62,9 @@ impl Default for ModalOf {
}
}
-impl PatternLinter for ModalOf {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ModalOf {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_toks: &[Token], source_chars: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/most_number.rs b/harper-core/src/linting/most_number.rs
index 536c155d5..a63c93edf 100644
--- a/harper-core/src/linting/most_number.rs
+++ b/harper-core/src/linting/most_number.rs
@@ -1,28 +1,28 @@
-use crate::{
- Token, TokenStringExt,
- patterns::{All, Pattern, SequencePattern, WordSet},
-};
+use crate::expr::All;
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::{Token, TokenStringExt, patterns::WordSet};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct MostNumber {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for MostNumber {
fn default() -> Self {
Self {
- pattern: Box::new(All::new(vec![
+ expr: Box::new(All::new(vec![
// Main pattern
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.t_aco("most")
.t_ws()
.then(WordSet::new(&["amount", "number"])),
),
// Context pattern
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_anything()
.then_anything()
.then_anything()
@@ -34,9 +34,9 @@ impl Default for MostNumber {
}
}
-impl PatternLinter for MostNumber {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for MostNumber {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/multiple_sequential_pronouns.rs b/harper-core/src/linting/multiple_sequential_pronouns.rs
index 2fd77d9c7..e71fe7250 100644
--- a/harper-core/src/linting/multiple_sequential_pronouns.rs
+++ b/harper-core/src/linting/multiple_sequential_pronouns.rs
@@ -1,13 +1,15 @@
use super::Suggestion;
-use super::pattern_linter::PatternLinter;
+use super::expr_linter::ExprLinter;
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::linting::LintKind;
-use crate::patterns::{Pattern, SequencePattern, WordSet};
+use crate::patterns::WordSet;
use crate::{CharStringExt, Lint, Lrc, Token, TokenStringExt};
/// Linter that checks if multiple pronouns are being used right after each
/// other. This is a common mistake to make during the revision process.
pub struct MultipleSequentialPronouns {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
subject_pronouns: Lrc<WordSet>,
object_pronouns: Lrc<WordSet>,
possessive_adjectives: Lrc<WordSet>,
@@ -45,11 +47,11 @@ impl MultipleSequentialPronouns {
]));
Self {
- pattern: Box::new(
- SequencePattern::default()
+ expr: Box::new(
+ SequenceExpr::default()
.then(pronouns.clone())
.then_one_or_more(
- SequencePattern::default()
+ SequenceExpr::default()
.then_whitespace()
.then(pronouns.clone()),
),
@@ -73,9 +75,9 @@ impl MultipleSequentialPronouns {
}
}
-impl PatternLinter for MultipleSequentialPronouns {
- fn pattern(&self) -> &dyn crate::patterns::Pattern {
- self.pattern.as_ref()
+impl ExprLinter for MultipleSequentialPronouns {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/nail_on_the_head.rs b/harper-core/src/linting/nail_on_the_head.rs
index b205f4b05..a436a0f08 100644
--- a/harper-core/src/linting/nail_on_the_head.rs
+++ b/harper-core/src/linting/nail_on_the_head.rs
@@ -1,17 +1,19 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{Pattern, SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::WordSet,
};
pub struct NailOnTheHead {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for NailOnTheHead {
fn default() -> Self {
let mis = WordSet::new(&["hat", "had", "hit", "hid"]);
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.t_aco("nail")
.then_whitespace()
.t_aco("on")
@@ -20,14 +22,14 @@ impl Default for NailOnTheHead {
.then_whitespace()
.then(mis);
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for NailOnTheHead {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for NailOnTheHead {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], _src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/no_oxford_comma.rs b/harper-core/src/linting/no_oxford_comma.rs
index 96860056a..34ae22f3a 100644
--- a/harper-core/src/linting/no_oxford_comma.rs
+++ b/harper-core/src/linting/no_oxford_comma.rs
@@ -1,20 +1,22 @@
+use crate::expr::ExprExt;
+use crate::expr::SequenceExpr;
use crate::{
Document, Token, TokenStringExt,
- patterns::{NominalPhrase, PatternExt, SequencePattern, WordSet},
+ patterns::{NominalPhrase, WordSet},
};
use super::{Lint, LintKind, Linter, Suggestion};
pub struct NoOxfordComma {
- pattern: SequencePattern,
+ expr: SequenceExpr,
}
impl NoOxfordComma {
pub fn new() -> Self {
Self {
- pattern: {
+ expr: {
let this = {
- let this = SequencePattern::default();
+ let this = SequenceExpr::default();
this.then(NominalPhrase)
}
.then_comma()
@@ -52,7 +54,7 @@ impl Linter for NoOxfordComma {
let mut lints = Vec::new();
for sentence in document.iter_sentences() {
- for match_span in self.pattern.iter_matches(sentence, document.get_source()) {
+ for match_span in self.expr.iter_matches(sentence, document.get_source()) {
let lint = self.match_to_lint(
&sentence[match_span.start..match_span.end],
document.get_source(),
diff --git a/harper-core/src/linting/nobody.rs b/harper-core/src/linting/nobody.rs
index 68b6d7403..32f9aad5e 100644
--- a/harper-core/src/linting/nobody.rs
+++ b/harper-core/src/linting/nobody.rs
@@ -1,30 +1,29 @@
-use crate::{
- Token, TokenStringExt,
- patterns::{Pattern, SequencePattern},
-};
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::{Token, TokenStringExt};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct Nobody {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for Nobody {
fn default() -> Self {
- let pattern = SequencePattern::aco("no")
+ let pattern = SequenceExpr::aco("no")
.then_whitespace()
.t_aco("body")
.then_whitespace()
.then_verb();
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for Nobody {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for Nobody {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/nominal_wants.rs b/harper-core/src/linting/nominal_wants.rs
index ac254c1cc..5d15a5d03 100644
--- a/harper-core/src/linting/nominal_wants.rs
+++ b/harper-core/src/linting/nominal_wants.rs
@@ -1,12 +1,14 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{Pattern, SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::WordSet,
word_metadata::Person,
};
pub struct NominalWants {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for NominalWants {
@@ -37,19 +39,19 @@ impl Default for NominalWants {
}
let miss = WordSet::new(&["wont", "wonts", "want", "wants"]);
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(is_applicable_pronoun)
.then_whitespace()
.then(miss);
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for NominalWants {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for NominalWants {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/noun_instead_of_verb.rs b/harper-core/src/linting/noun_instead_of_verb.rs
index c938f350a..9550c2d4a 100644
--- a/harper-core/src/linting/noun_instead_of_verb.rs
+++ b/harper-core/src/linting/noun_instead_of_verb.rs
@@ -1,9 +1,9 @@
-use crate::{
- Lrc, Token, TokenStringExt,
- patterns::{LongestMatchOf, Pattern, SequencePattern, WordSet},
-};
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
+use crate::{Lrc, Token, TokenStringExt, patterns::WordSet};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
/// Common noun-verb pairs that are often confused
const NOUN_VERB_PAIRS: &[(&str, &str)] = &[
@@ -50,7 +50,7 @@ const MODAL_VERBS_ETC: &[&str] = &[
/// Linter that corrects common noun/verb confusions
pub struct NounInsteadOfVerb {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for NounInsteadOfVerb {
@@ -69,23 +69,23 @@ impl Default for NounInsteadOfVerb {
));
let basic_pattern = Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(pre_context)
.then_whitespace()
.then(nouns.clone()),
);
- let pattern_followed_by_punctuation = SequencePattern::default()
+ let pattern_followed_by_punctuation = SequenceExpr::default()
.then(basic_pattern.clone())
.then_punctuation();
- let pattern_followed_by_word = SequencePattern::default()
+ let pattern_followed_by_word = SequenceExpr::default()
.then(basic_pattern.clone())
.then_whitespace()
.then_any_word();
Self {
- pattern: Box::new(LongestMatchOf::new(vec![
+ expr: Box::new(LongestMatchOf::new(vec![
Box::new(pattern_followed_by_punctuation),
Box::new(pattern_followed_by_word),
Box::new(basic_pattern),
@@ -94,9 +94,9 @@ impl Default for NounInsteadOfVerb {
}
}
-impl PatternLinter for NounInsteadOfVerb {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for NounInsteadOfVerb {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/of_course.rs b/harper-core/src/linting/of_course.rs
index 3828b2f50..7c5402fe7 100644
--- a/harper-core/src/linting/of_course.rs
+++ b/harper-core/src/linting/of_course.rs
@@ -1,30 +1,32 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::WordSet,
};
pub struct OfCourse {
- pattern: Box<dyn crate::patterns::Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for OfCourse {
fn default() -> Self {
let wrong_forms = WordSet::new(&["curse", "corse"]);
- let pattern = SequencePattern::default()
+ let expr = SequenceExpr::default()
.t_aco("of")
.then_whitespace()
.then(wrong_forms);
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(expr),
}
}
}
-impl PatternLinter for OfCourse {
- fn pattern(&self) -> &dyn crate::patterns::Pattern {
- self.pattern.as_ref()
+impl ExprLinter for OfCourse {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/one_and_the_same.rs b/harper-core/src/linting/one_and_the_same.rs
index 6488500aa..b854ab6d2 100644
--- a/harper-core/src/linting/one_and_the_same.rs
+++ b/harper-core/src/linting/one_and_the_same.rs
@@ -1,12 +1,13 @@
-use crate::{
- Lrc, Token, TokenStringExt,
- patterns::{FixedPhrase, LongestMatchOf, Pattern, SequencePattern, WordSet},
-};
+use crate::expr::Expr;
+use crate::expr::FixedPhrase;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
+use crate::{Lrc, Token, TokenStringExt, patterns::WordSet};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct OneAndTheSame {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for OneAndTheSame {
@@ -14,15 +15,15 @@ impl Default for OneAndTheSame {
let one_in_the_same = Lrc::new(FixedPhrase::from_phrase("one in the same"));
Self {
- pattern: Box::new(LongestMatchOf::new(vec![
+ expr: Box::new(LongestMatchOf::new(vec![
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(WordSet::new(&["are", "were"]))
.t_ws()
.then(one_in_the_same.clone()),
),
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(one_in_the_same.clone())
.t_ws()
.t_aco("as"),
@@ -32,13 +33,13 @@ impl Default for OneAndTheSame {
}
}
-fn ws_word(word: &'static str) -> SequencePattern {
- SequencePattern::default().t_ws().t_aco(word)
+fn ws_word(word: &'static str) -> SequenceExpr {
+ SequenceExpr::default().t_ws().t_aco(word)
}
-impl PatternLinter for OneAndTheSame {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for OneAndTheSame {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/open_compounds.rs b/harper-core/src/linting/open_compounds.rs
index 174059ebc..4a4cd800a 100644
--- a/harper-core/src/linting/open_compounds.rs
+++ b/harper-core/src/linting/open_compounds.rs
@@ -1,13 +1,13 @@
-use crate::{
- Lrc, Token,
- patterns::{LongestMatchOf, Pattern, SequencePattern, WordSet},
-};
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
+use crate::{Lrc, Token, patterns::WordSet};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
use hashbrown::HashMap;
pub struct OpenCompounds {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
compound_to_phrase: HashMap<String, String>,
}
@@ -37,23 +37,23 @@ impl Default for OpenCompounds {
for compound in compound_to_phrase.keys().cloned().collect::<Vec<_>>() {
compound_wordset.add(&compound);
}
- let compound = Lrc::new(SequencePattern::default().then(compound_wordset));
+ let compound = Lrc::new(SequenceExpr::default().then(compound_wordset));
- let with_prev = SequencePattern::default()
+ let with_prev = SequenceExpr::default()
.then_anything()
.then(compound.clone());
- let with_next = SequencePattern::default()
+ let with_next = SequenceExpr::default()
.then(compound.clone())
.then_anything();
- let with_prev_and_next = SequencePattern::default()
+ let with_prev_and_next = SequenceExpr::default()
.then_anything()
.then(compound.clone())
.then_anything();
Self {
- pattern: Box::new(LongestMatchOf::new(vec![
+ expr: Box::new(LongestMatchOf::new(vec![
Box::new(with_prev_and_next),
Box::new(with_prev),
Box::new(with_next),
@@ -64,9 +64,9 @@ impl Default for OpenCompounds {
}
}
-impl PatternLinter for OpenCompounds {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for OpenCompounds {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_toks: &[Token], source_chars: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/open_the_light.rs b/harper-core/src/linting/open_the_light.rs
index fb9d8c984..e964a6925 100644
--- a/harper-core/src/linting/open_the_light.rs
+++ b/harper-core/src/linting/open_the_light.rs
@@ -1,13 +1,16 @@
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
use crate::{
Lrc, Token, TokenStringExt,
linting::{LintKind, Suggestion},
- patterns::{LongestMatchOf, Pattern, SequencePattern, WordSet},
+ patterns::WordSet,
};
-use super::{Lint, PatternLinter};
+use super::{ExprLinter, Lint};
pub struct OpenTheLight {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for OpenTheLight {
@@ -32,7 +35,7 @@ impl Default for OpenTheLight {
];
let open_the_device = Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(WordSet::new(TO_OPEN))
.t_ws()
.then_determiner()
@@ -40,23 +43,23 @@ impl Default for OpenTheLight {
.then(WordSet::new(DEVICES)),
);
- let open_the_device_then_noun = SequencePattern::default()
+ let open_the_device_then_noun = SequenceExpr::default()
.then(open_the_device.clone())
.t_ws()
.then_noun();
- let pattern = Box::new(LongestMatchOf::new(vec![
+ let expr = Box::new(LongestMatchOf::new(vec![
Box::new(open_the_device),
Box::new(open_the_device_then_noun),
]));
- Self { pattern }
+ Self { expr }
}
}
-impl PatternLinter for OpenTheLight {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for OpenTheLight {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/out_of_date.rs b/harper-core/src/linting/out_of_date.rs
index b5e5c7d23..9911b62fe 100644
--- a/harper-core/src/linting/out_of_date.rs
+++ b/harper-core/src/linting/out_of_date.rs
@@ -1,12 +1,12 @@
-use crate::{
- Token, TokenStringExt,
- patterns::{FixedPhrase, LongestMatchOf, Pattern},
-};
+use crate::expr::Expr;
+use crate::expr::FixedPhrase;
+use crate::expr::LongestMatchOf;
+use crate::{Token, TokenStringExt};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct OutOfDate {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for OutOfDate {
@@ -18,14 +18,14 @@ impl Default for OutOfDate {
]);
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for OutOfDate {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for OutOfDate {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/oxford_comma.rs b/harper-core/src/linting/oxford_comma.rs
index 6d58ec9f3..d1f2b84e4 100644
--- a/harper-core/src/linting/oxford_comma.rs
+++ b/harper-core/src/linting/oxford_comma.rs
@@ -1,31 +1,31 @@
-use crate::{
- Lrc, Token, TokenStringExt,
- linting::Linter,
- patterns::{OwnedPatternExt, Pattern, PatternExt, SequencePattern, WordSet},
-};
+use crate::expr::Expr;
+use crate::expr::ExprExt;
+use crate::expr::OwnedExprExt;
+use crate::expr::SequenceExpr;
+use crate::{Lrc, Token, TokenStringExt, linting::Linter, patterns::WordSet};
use super::{super::Lint, LintKind, Suggestion};
pub struct OxfordComma {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for OxfordComma {
fn default() -> Self {
let item = Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_determiner()
.then_whitespace()
.then_nominal()
- .or(SequencePattern::default().then_nominal()),
+ .or(SequenceExpr::default().then_nominal()),
);
- let item_chunk = SequencePattern::default()
+ let item_chunk = SequenceExpr::default()
.then(item.clone())
.then_comma()
.then_whitespace();
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then_one_or_more(item_chunk)
.then(item.clone())
.then_whitespace()
@@ -34,7 +34,7 @@ impl Default for OxfordComma {
.then(item.clone());
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
@@ -76,7 +76,7 @@ impl Linter for OxfordComma {
let sentence = &sentence[skip..];
- for match_span in self.pattern.iter_matches(sentence, document.get_source()) {
+ for match_span in self.expr.iter_matches(sentence, document.get_source()) {
let lint = self.match_to_lint(
&sentence[match_span.start..match_span.end],
document.get_source(),
diff --git a/harper-core/src/linting/oxymorons.rs b/harper-core/src/linting/oxymorons.rs
index 9a5e71c42..ed3bd56fd 100644
--- a/harper-core/src/linting/oxymorons.rs
+++ b/harper-core/src/linting/oxymorons.rs
@@ -1,10 +1,12 @@
-use crate::linting::{Lint, LintKind, PatternLinter};
-use crate::patterns::{FixedPhrase, LongestMatchOf, Pattern};
+use crate::expr::Expr;
+use crate::expr::FixedPhrase;
+use crate::expr::LongestMatchOf;
+use crate::linting::{ExprLinter, Lint, LintKind};
use crate::{Token, TokenStringExt};
/// A linter that flags oxymoronic phrases.
pub struct Oxymorons {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Oxymorons {
@@ -31,13 +33,13 @@ impl Oxymorons {
];
// Build a vector of exact-match patterns for each oxymoron.
- let patterns: Vec<Box<dyn Pattern>> = phrases
+ let exprs: Vec<Box<dyn Expr>> = phrases
.into_iter()
- .map(|s| Box::new(FixedPhrase::from_phrase(s)) as Box<dyn Pattern>)
+ .map(|s| Box::new(FixedPhrase::from_phrase(s)) as Box<dyn Expr>)
.collect();
- let pattern = Box::new(LongestMatchOf::new(patterns));
- Self { pattern }
+ let expr = Box::new(LongestMatchOf::new(exprs));
+ Self { expr }
}
}
@@ -47,10 +49,10 @@ impl Default for Oxymorons {
}
}
-impl PatternLinter for Oxymorons {
+impl ExprLinter for Oxymorons {
/// Returns the underlying pattern.
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/phrase_corrections/mod.rs b/harper-core/src/linting/phrase_corrections/mod.rs
index bcb7655e6..ea71bd04e 100644
--- a/harper-core/src/linting/phrase_corrections/mod.rs
+++ b/harper-core/src/linting/phrase_corrections/mod.rs
@@ -13,7 +13,7 @@ pub fn lint_group() -> LintGroup {
$($name:expr => ($input:expr, $corrections:expr, $hint:expr, $description:expr)),+ $(,)?
}) => {
$(
- $group.add_pattern_linter(
+ $group.add_expr_linter(
$name,
Box::new(
MapPhraseLinter::new_fixed_phrases(
diff --git a/harper-core/src/linting/pique_interest.rs b/harper-core/src/linting/pique_interest.rs
index e2c128121..8a7b515d2 100644
--- a/harper-core/src/linting/pique_interest.rs
+++ b/harper-core/src/linting/pique_interest.rs
@@ -1,18 +1,16 @@
-use crate::{
- CharString, CharStringExt, Token,
- char_string::char_string,
- patterns::{Pattern, SequencePattern, WordSet},
-};
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::{CharString, CharStringExt, Token, char_string::char_string, patterns::WordSet};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct PiqueInterest {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for PiqueInterest {
fn default() -> Self {
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(WordSet::new(&[
"peak", "peaked", "peek", "peeked", "peeking", "peaking",
]))
@@ -22,7 +20,7 @@ impl Default for PiqueInterest {
.t_aco("interest");
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
@@ -41,9 +39,9 @@ impl PiqueInterest {
}
}
-impl PatternLinter for PiqueInterest {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for PiqueInterest {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/possessive_your.rs b/harper-core/src/linting/possessive_your.rs
index 51d0be12c..7b2f102f7 100644
--- a/harper-core/src/linting/possessive_your.rs
+++ b/harper-core/src/linting/possessive_your.rs
@@ -1,18 +1,17 @@
-use crate::{
- Token,
- patterns::{Pattern, SequencePattern},
-};
+use crate::Token;
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct PossessiveYour {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for PossessiveYour {
fn default() -> Self {
let pattern =
- SequencePattern::aco("you")
+ SequenceExpr::aco("you")
.then_whitespace()
.then(|tok: &Token, source: &[char]| {
if tok.kind.is_nominal() && !tok.kind.is_likely_homograph() {
@@ -23,14 +22,14 @@ impl Default for PossessiveYour {
});
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for PossessiveYour {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for PossessiveYour {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/pronoun_contraction/avoid_contraction.rs b/harper-core/src/linting/pronoun_contraction/avoid_contraction.rs
index 14021a082..48b157629 100644
--- a/harper-core/src/linting/pronoun_contraction/avoid_contraction.rs
+++ b/harper-core/src/linting/pronoun_contraction/avoid_contraction.rs
@@ -1,31 +1,31 @@
-use crate::{
- Token,
- patterns::{Pattern, SequencePattern},
-};
+use crate::Token;
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
-use super::super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct AvoidContraction {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for AvoidContraction {
fn default() -> Self {
- let pattern = SequencePattern::aco("you're").then_whitespace().then(
- |tok: &Token, _source: &[char]| {
- tok.kind.is_nominal() && !tok.kind.is_likely_homograph()
- },
- );
+ let pattern =
+ SequenceExpr::aco("you're")
+ .then_whitespace()
+ .then(|tok: &Token, _source: &[char]| {
+ tok.kind.is_nominal() && !tok.kind.is_likely_homograph()
+ });
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for AvoidContraction {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for AvoidContraction {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/pronoun_contraction/should_contract.rs b/harper-core/src/linting/pronoun_contraction/should_contract.rs
index a47888e54..ad3539676 100644
--- a/harper-core/src/linting/pronoun_contraction/should_contract.rs
+++ b/harper-core/src/linting/pronoun_contraction/should_contract.rs
@@ -1,10 +1,9 @@
-use crate::{
- CharStringExt, Token,
- patterns::{Pattern, SequencePattern, WordSet},
-};
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::{CharStringExt, Token, patterns::WordSet};
use crate::Lint;
-use crate::linting::{LintKind, PatternLinter, Suggestion};
+use crate::linting::{ExprLinter, LintKind, Suggestion};
/// See also:
/// harper-core/src/linting/compound_nouns/implied_ownership_compound_nouns.rs
@@ -12,14 +11,14 @@ use crate::linting::{LintKind, PatternLinter, Suggestion};
/// harper-core/src/linting/lets_confusion/let_us_redundancy.rs
/// harper-core/src/linting/lets_confusion/no_contraction_with_verb.rs
pub struct ShouldContract {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ShouldContract {
fn default() -> Self {
Self {
- pattern: Box::new(
- SequencePattern::default()
+ expr: Box::new(
+ SequenceExpr::default()
.then(WordSet::new(&["your", "were"]))
.then_whitespace()
.then_determiner()
@@ -42,9 +41,9 @@ impl ShouldContract {
}
}
-impl PatternLinter for ShouldContract {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ShouldContract {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/pronoun_knew.rs b/harper-core/src/linting/pronoun_knew.rs
index 34109d82a..626f91bf1 100644
--- a/harper-core/src/linting/pronoun_knew.rs
+++ b/harper-core/src/linting/pronoun_knew.rs
@@ -1,11 +1,14 @@
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{LongestMatchOf, SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::WordSet,
};
pub struct PronounKnew {
- pattern: Box<dyn crate::patterns::Pattern>,
+ expr: Box<dyn Expr>,
}
trait PronounKnewExt {
@@ -27,12 +30,12 @@ impl Default for PronounKnew {
!excluded.contains(&&*pronorm)
};
- let pronoun_then_new = SequencePattern::default()
+ let pronoun_then_new = SequenceExpr::default()
.then(pronoun_pattern)
.then_whitespace()
.then_any_capitalization_of("new");
- let pronoun_adverb_then_new = SequencePattern::default()
+ let pronoun_adverb_then_new = SequenceExpr::default()
.then(pronoun_pattern)
.then_whitespace()
.then(WordSet::new(&["always", "never", "also", "often"]))
@@ -45,14 +48,14 @@ impl Default for PronounKnew {
]);
Self {
- pattern: Box::new(combined_pattern),
+ expr: Box::new(combined_pattern),
}
}
}
-impl PatternLinter for PronounKnew {
- fn pattern(&self) -> &dyn crate::patterns::Pattern {
- self.pattern.as_ref()
+impl ExprLinter for PronounKnew {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/proper_noun_capitalization_linters.rs b/harper-core/src/linting/proper_noun_capitalization_linters.rs
index 92e0e25c0..38db9fb53 100644
--- a/harper-core/src/linting/proper_noun_capitalization_linters.rs
+++ b/harper-core/src/linting/proper_noun_capitalization_linters.rs
@@ -1,10 +1,10 @@
+use crate::expr::{Expr, ExprMap, FixedPhrase};
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
+use super::{ExprLinter, LintGroup};
use super::{Lint, LintKind, Suggestion};
-use super::{LintGroup, PatternLinter};
use crate::parsers::PlainEnglish;
-use crate::patterns::{FixedPhrase, Pattern, PatternMap};
use crate::{Dictionary, Document};
use crate::{Token, TokenStringExt};
use std::sync::Arc;
@@ -14,7 +14,7 @@ use std::sync::Arc;
///
/// If you would like to add a proper noun to Harper, see `proper_noun_rules.json`.
pub struct ProperNounCapitalizationLinter<D: Dictionary + 'static> {
- pattern_map: PatternMap<Document>,
+ pattern_map: ExprMap<Document>,
description: String,
dictionary: Arc<D>,
}
@@ -43,7 +43,7 @@ impl<D: Dictionary + 'static> ProperNounCapitalizationLinter<D> {
) -> Self {
let dictionary = Arc::new(dictionary);
- let mut pattern_map = PatternMap::default();
+ let mut expr_map = ExprMap::default();
for can_vers in canonical_versions {
let doc = Document::new_from_vec(
@@ -51,26 +51,26 @@ impl<D: Dictionary + 'static> ProperNounCapitalizationLinter<D> {
&PlainEnglish,
&dictionary,
);
- let pattern = FixedPhrase::from_document(&doc);
+ let expr = FixedPhrase::from_document(&doc);
- pattern_map.insert(pattern, doc);
+ expr_map.insert(expr, doc);
}
Self {
- pattern_map,
+ pattern_map: expr_map,
dictionary: dictionary.clone(),
description: description.to_string(),
}
}
}
-impl<D: Dictionary + 'static> PatternLinter for ProperNounCapitalizationLinter<D> {
- fn pattern(&self) -> &dyn Pattern {
+impl<D: Dictionary + 'static> ExprLinter for ProperNounCapitalizationLinter<D> {
+ fn expr(&self) -> &dyn Expr {
&self.pattern_map
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
- let canonical_case = self.pattern_map.lookup(matched_tokens, source).unwrap();
+ let canonical_case = self.pattern_map.lookup(0, matched_tokens, source).unwrap();
let mut broken = false;
@@ -116,7 +116,7 @@ fn lint_group_from_json(json: &str, dictionary: Arc<impl Dictionary + 'static>)
let rules: HashMap<String, RuleEntry> = serde_json::from_str(json).unwrap();
for (key, rule) in rules.into_iter() {
- group.add_pattern_linter(
+ group.add_expr_linter(
key,
Box::new(ProperNounCapitalizationLinter::new_strs(
rule.canonical,
diff --git a/harper-core/src/linting/save_to_safe.rs b/harper-core/src/linting/save_to_safe.rs
index caa8bd8f1..d86b1d35e 100644
--- a/harper-core/src/linting/save_to_safe.rs
+++ b/harper-core/src/linting/save_to_safe.rs
@@ -1,16 +1,19 @@
+use crate::expr::Expr;
+use crate::expr::OwnedExprExt;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{InflectionOfBe, OwnedPatternExt, Pattern, SequencePattern, Word},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::{InflectionOfBe, Word},
};
pub struct SaveToSafe {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for SaveToSafe {
fn default() -> Self {
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(InflectionOfBe::new().or(Word::new("it")))
.then_whitespace()
.t_aco("save")
@@ -19,14 +22,14 @@ impl Default for SaveToSafe {
.then_whitespace()
.then_verb();
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for SaveToSafe {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for SaveToSafe {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/since_duration.rs b/harper-core/src/linting/since_duration.rs
index 6c55d62fb..715479d6d 100644
--- a/harper-core/src/linting/since_duration.rs
+++ b/harper-core/src/linting/since_duration.rs
@@ -1,9 +1,10 @@
-use crate::{
- Lrc, Token, TokenStringExt,
- patterns::{LongestMatchOf, Pattern, SequencePattern, SpelledNumberPattern, WordSet},
-};
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
+use crate::expr::SpelledNumberExpr;
+use crate::{Lrc, Token, TokenStringExt, patterns::WordSet};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
const AGO_VARIANTS: [&[char]; 3] = [&['a', 'g', 'o'], &['A', 'g', 'o'], &['A', 'G', 'O']];
const FOR_VARIANTS: [&[char]; 3] = [&['f', 'o', 'r'], &['F', 'o', 'r'], &['F', 'O', 'R']];
@@ -21,7 +22,7 @@ fn match_case_string<'a>(template: &[char], variants: [&'a [char]; 3]) -> &'a [c
}
pub struct SinceDuration {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for SinceDuration {
@@ -32,24 +33,24 @@ impl Default for SinceDuration {
]);
let pattern_without_ago = Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_any_capitalization_of("since")
.then_whitespace()
.then(LongestMatchOf::new(vec![
- Box::new(SpelledNumberPattern),
- Box::new(SequencePattern::default().then_number()),
+ Box::new(SpelledNumberExpr),
+ Box::new(SequenceExpr::default().then_number()),
]))
.then_whitespace()
.then(units),
);
- let pattern_with_ago = SequencePattern::default()
+ let pattern_with_ago = SequenceExpr::default()
.then(pattern_without_ago.clone())
.then_whitespace()
.then_any_capitalization_of("ago");
Self {
- pattern: Box::new(LongestMatchOf::new(vec![
+ expr: Box::new(LongestMatchOf::new(vec![
Box::new(pattern_without_ago),
Box::new(pattern_with_ago),
])),
@@ -57,9 +58,9 @@ impl Default for SinceDuration {
}
}
-impl PatternLinter for SinceDuration {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for SinceDuration {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/somewhat_something.rs b/harper-core/src/linting/somewhat_something.rs
index 680196156..d518cb1c8 100644
--- a/harper-core/src/linting/somewhat_something.rs
+++ b/harper-core/src/linting/somewhat_something.rs
@@ -1,31 +1,30 @@
-use crate::{
- Token,
- patterns::{Pattern, SequencePattern},
-};
+use crate::Token;
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct SomewhatSomething {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for SomewhatSomething {
fn default() -> Self {
- let pattern = SequencePattern::aco("somewhat")
+ let pattern = SequenceExpr::aco("somewhat")
.then_whitespace()
.t_aco("of")
.then_whitespace()
.t_aco("a");
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for SomewhatSomething {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for SomewhatSomething {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/that_which.rs b/harper-core/src/linting/that_which.rs
index cafd7fa4b..5b73fb98f 100644
--- a/harper-core/src/linting/that_which.rs
+++ b/harper-core/src/linting/that_which.rs
@@ -1,22 +1,22 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::expr::WordExprGroup;
use itertools::Itertools;
-use crate::{
- Lrc, Token, TokenStringExt,
- patterns::{Pattern, SequencePattern, WordPatternGroup},
-};
+use crate::{Lrc, Token, TokenStringExt};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct ThatWhich {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for ThatWhich {
fn default() -> Self {
- let mut pattern = WordPatternGroup::default();
+ let mut pattern = WordExprGroup::default();
let matching_pattern = Lrc::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_any_capitalization_of("that")
.then_whitespace()
.then_any_capitalization_of("that"),
@@ -26,14 +26,14 @@ impl Default for ThatWhich {
pattern.add("That", Box::new(matching_pattern));
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for ThatWhich {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ThatWhich {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/the_how_why.rs b/harper-core/src/linting/the_how_why.rs
index 03839d7e9..1b2226678 100644
--- a/harper-core/src/linting/the_how_why.rs
+++ b/harper-core/src/linting/the_how_why.rs
@@ -1,53 +1,53 @@
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
use crate::{
Token, TokenStringExt,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{Invert, LongestMatchOf, Pattern, SequencePattern},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
};
/// Suggests removing `the` when followed by how/why/who/when/what,
/// skipping cases like `how to` and `who's who`.
pub struct TheHowWhy {
- pattern: LongestMatchOf,
+ expr: LongestMatchOf,
}
impl Default for TheHowWhy {
fn default() -> Self {
- let the_how = SequencePattern::default()
+ let the_how = SequenceExpr::default()
.t_aco("the")
.then_whitespace()
.t_aco("how")
- .then(Invert::new(
- SequencePattern::default().then_whitespace().t_aco("to"),
- ));
+ .if_not_then_step_one(SequenceExpr::default().then_whitespace().t_aco("to"));
- let the_who = SequencePattern::default()
+ let the_who = SequenceExpr::default()
.t_aco("the")
.then_whitespace()
.t_aco("who")
- .then(Invert::new(
- SequencePattern::default()
+ .if_not_then_step_one(
+ SequenceExpr::default()
.then_whitespace()
.t_aco("'s")
.then_whitespace()
.t_aco("who"),
- ));
+ );
- let the_why = SequencePattern::default()
+ let the_why = SequenceExpr::default()
.t_aco("the")
.then_whitespace()
.t_aco("why");
- let the_when = SequencePattern::default()
+ let the_when = SequenceExpr::default()
.t_aco("the")
.then_whitespace()
.t_aco("when");
- let the_what = SequencePattern::default()
+ let the_what = SequenceExpr::default()
.t_aco("the")
.then_whitespace()
.t_aco("what");
- let pattern = LongestMatchOf::new(vec![
+ let expr = LongestMatchOf::new(vec![
Box::new(the_how),
Box::new(the_who),
Box::new(the_why),
@@ -55,13 +55,13 @@ impl Default for TheHowWhy {
Box::new(the_what),
]);
- Self { pattern }
+ Self { expr }
}
}
-impl PatternLinter for TheHowWhy {
- fn pattern(&self) -> &dyn Pattern {
- &self.pattern
+impl ExprLinter for TheHowWhy {
+ fn expr(&self) -> &dyn Expr {
+ &self.expr
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/the_my.rs b/harper-core/src/linting/the_my.rs
index 6788b5a4e..e8d0fe44e 100644
--- a/harper-core/src/linting/the_my.rs
+++ b/harper-core/src/linting/the_my.rs
@@ -1,11 +1,14 @@
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
use crate::{
CharStringExt, Token, TokenStringExt,
- patterns::{LongestMatchOf, Pattern, SequencePattern, Word, WordSet},
+ patterns::{Word, WordSet},
};
pub struct TheMy {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for TheMy {
@@ -13,18 +16,18 @@ impl Default for TheMy {
let the = Word::new("the");
let any_possessive = WordSet::new(&["my", "your", "his", "her", "its", "our", "their"]);
- let the_poss = SequencePattern::default()
+ let the_poss = SequenceExpr::default()
.then(the.clone())
.then_whitespace()
.then(any_possessive.clone());
- let poss_the = SequencePattern::default()
+ let poss_the = SequenceExpr::default()
.then(any_possessive)
.then_whitespace()
.then(the);
Self {
- pattern: Box::new(LongestMatchOf::new(vec![
+ expr: Box::new(LongestMatchOf::new(vec![
Box::new(the_poss),
Box::new(poss_the),
])),
@@ -32,9 +35,9 @@ impl Default for TheMy {
}
}
-impl PatternLinter for TheMy {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for TheMy {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/then_than.rs b/harper-core/src/linting/then_than.rs
index 5859f4007..a6b09ed33 100644
--- a/harper-core/src/linting/then_than.rs
+++ b/harper-core/src/linting/then_than.rs
@@ -1,23 +1,26 @@
-use super::{Lint, LintKind, PatternLinter};
+use super::{ExprLinter, Lint, LintKind};
use crate::Token;
+use crate::expr::All;
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::OwnedExprExt;
+use crate::expr::SequenceExpr;
use crate::linting::Suggestion;
-use crate::patterns::{
- All, Invert, LongestMatchOf, OwnedPatternExt, Pattern, SequencePattern, Word, WordSet,
-};
+use crate::patterns::{Invert, Word, WordSet};
-#[doc = "Corrects the misuse of `then` to `than`."]
+/// Corrects the misuse of `then` to `than`.
pub struct ThenThan {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl ThenThan {
pub fn new() -> Self {
Self {
- pattern: Box::new(All::new(vec![
+ expr: Box::new(All::new(vec![
Box::new(LongestMatchOf::new(vec![
// Comparative form of adjective
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(Word::new("other").or(Box::new(
|tok: &Token, source: &[char]| {
is_comparative_adjective(tok, source)
@@ -26,11 +29,11 @@ impl ThenThan {
.t_ws()
.t_aco("then")
.t_ws()
- .then(Invert::new(Word::new("that"))),
+ .if_not_then_step_one(Word::new("that")),
),
// Positive form of adjective following "more" or "less"
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then(WordSet::new(&["more", "less"]))
.t_ws()
.then(|tok: &Token, _source: &[char]| {
@@ -39,7 +42,7 @@ impl ThenThan {
.t_ws()
.t_aco("then")
.t_ws()
- .then(Invert::new(Word::new("that"))),
+ .if_not_then_step_one(Word::new("that")),
),
])),
// Exceptions to the rule.
@@ -70,9 +73,9 @@ impl Default for ThenThan {
}
}
-impl PatternLinter for ThenThan {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ThenThan {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
// For both "stupider then X" and "more stupid then X", "then" is 3rd last token.
diff --git a/harper-core/src/linting/use_genitive.rs b/harper-core/src/linting/use_genitive.rs
index fc5d82184..0ed87d834 100644
--- a/harper-core/src/linting/use_genitive.rs
+++ b/harper-core/src/linting/use_genitive.rs
@@ -1,61 +1,65 @@
-use crate::linting::{LintKind, PatternLinter, Suggestion};
-use crate::patterns::{Invert, LongestMatchOf, Pattern, SequencePattern, WordPatternGroup};
+use crate::expr::Expr;
+use crate::expr::LongestMatchOf;
+use crate::expr::SequenceExpr;
+use crate::expr::WordExprGroup;
+use crate::linting::{ExprLinter, LintKind, Suggestion};
+use crate::patterns::Word;
use crate::{Lint, Lrc, Token};
// Looks for places where the genitive case _isn't_ being used, and should be.
pub struct UseGenitive {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl UseGenitive {
fn new() -> Self {
// Define the environment in which the genitive case __should__ be used.
- let environment = Lrc::new(SequencePattern::default().then_whitespace().then(
+ let environment = Lrc::new(SequenceExpr::default().then_whitespace().then(
LongestMatchOf::new(vec![
Box::new(
- SequencePattern::default()
+ SequenceExpr::default()
.then_one_or_more_adjectives()
.then_whitespace()
.then_noun(),
),
- Box::new(SequencePattern::default().then_noun()),
+ Box::new(SequenceExpr::default().then_noun()),
]),
));
let trigger_words = ["there", "they're"];
- let mut primary_pattern = WordPatternGroup::default();
+ let mut primary_pattern = WordExprGroup::default();
for word in trigger_words {
primary_pattern.add(
word,
Box::new(
- SequencePattern::default()
- .then_exact_word(word)
+ SequenceExpr::default()
+ .then(Word::new_exact(word))
.then(environment.clone()),
),
)
}
// Add a prelude to remove false-positives.
- let full_pattern = SequencePattern::default()
- .then(Invert::new(LongestMatchOf::new(vec![
- Box::new(SequencePattern::default().t_aco("is")),
- Box::new(SequencePattern::default().t_aco("were")),
- Box::new(SequencePattern::default().then_adjective()),
- ])))
+ let full_pattern = SequenceExpr::default()
+ .if_not_then_step_one(LongestMatchOf::new(vec![
+ Box::new(SequenceExpr::default().t_aco("is")),
+ Box::new(SequenceExpr::default().t_aco("were")),
+ Box::new(SequenceExpr::default().then_adjective()),
+ ]))
.then_whitespace()
.then(primary_pattern);
Self {
- pattern: Box::new(full_pattern),
+ expr: Box::new(full_pattern),
}
}
}
-impl PatternLinter for UseGenitive {
- fn pattern(&self) -> &dyn crate::patterns::Pattern {
- self.pattern.as_ref()
+impl ExprLinter for UseGenitive {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], _source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/was_aloud.rs b/harper-core/src/linting/was_aloud.rs
index 4ff04fc1a..b486d1ad8 100644
--- a/harper-core/src/linting/was_aloud.rs
+++ b/harper-core/src/linting/was_aloud.rs
@@ -1,29 +1,31 @@
-use super::{Lint, LintKind, PatternLinter};
+use super::{ExprLinter, Lint, LintKind};
use crate::Token;
use crate::TokenStringExt;
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::linting::Suggestion;
-use crate::patterns::{Pattern, SequencePattern, WordSet};
+use crate::patterns::WordSet;
pub struct WasAloud {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for WasAloud {
fn default() -> Self {
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(WordSet::new(&["was", "were", "be", "been"]))
.then_whitespace()
.then_exact_word("aloud");
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for WasAloud {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for WasAloud {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/whereas.rs b/harper-core/src/linting/whereas.rs
index 8b37b39a4..67c971a5c 100644
--- a/harper-core/src/linting/whereas.rs
+++ b/harper-core/src/linting/whereas.rs
@@ -1,30 +1,29 @@
-use crate::{
- Token, TokenStringExt,
- patterns::{Pattern, SequencePattern},
-};
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
+use crate::{Token, TokenStringExt};
-use super::{Lint, LintKind, PatternLinter, Suggestion};
+use super::{ExprLinter, Lint, LintKind, Suggestion};
pub struct Whereas {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for Whereas {
fn default() -> Self {
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.t_aco("where")
.then_whitespace()
.t_aco("as");
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for Whereas {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for Whereas {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/widely_accepted.rs b/harper-core/src/linting/widely_accepted.rs
index 2bb36df61..f9dc862dd 100644
--- a/harper-core/src/linting/widely_accepted.rs
+++ b/harper-core/src/linting/widely_accepted.rs
@@ -1,27 +1,29 @@
+use crate::expr::Expr;
+use crate::expr::SequenceExpr;
use crate::{
Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{Pattern, SequencePattern, Word, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::{Word, WordSet},
};
pub struct WidelyAccepted {
- pattern: SequencePattern,
+ expr: SequenceExpr,
}
impl Default for WidelyAccepted {
fn default() -> Self {
- let pattern = SequencePattern::default()
+ let expr = SequenceExpr::default()
.then(Word::new("wide"))
.then_whitespace()
.then(WordSet::new(&["accepted", "acceptable", "used"]));
- Self { pattern }
+ Self { expr }
}
}
-impl PatternLinter for WidelyAccepted {
- fn pattern(&self) -> &dyn Pattern {
- &self.pattern
+impl ExprLinter for WidelyAccepted {
+ fn expr(&self) -> &dyn Expr {
+ &self.expr
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/linting/win_prize.rs b/harper-core/src/linting/win_prize.rs
index 821f62fc3..03b892906 100644
--- a/harper-core/src/linting/win_prize.rs
+++ b/harper-core/src/linting/win_prize.rs
@@ -1,11 +1,13 @@
+use crate::expr::SequenceExpr;
+use crate::expr::{Expr, OwnedExprExt};
use crate::{
Lrc, Token,
- linting::{Lint, LintKind, PatternLinter, Suggestion},
- patterns::{OwnedPatternExt, Pattern, SequencePattern, WordSet},
+ linting::{ExprLinter, Lint, LintKind, Suggestion},
+ patterns::WordSet,
};
pub struct WinPrize {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for WinPrize {
@@ -13,26 +15,26 @@ impl Default for WinPrize {
let verbs = Lrc::new(WordSet::new(&["win", "wins", "won", "winning"]));
let miss = Lrc::new(WordSet::new(&["price", "prices", "prise", "prises"]));
- let pattern = SequencePattern::default()
+ let pattern = SequenceExpr::default()
.then(verbs.clone())
.then_whitespace()
.then_determiner()
.then_whitespace()
.then(miss.clone())
- .or(SequencePattern::default()
+ .or(SequenceExpr::default()
.then(verbs)
.then_whitespace()
.then(miss));
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(pattern),
}
}
}
-impl PatternLinter for WinPrize {
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for WinPrize {
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {
diff --git a/harper-core/src/parsers/collapse_identifiers.rs b/harper-core/src/parsers/collapse_identifiers.rs
index c13ee0fa9..80de35e9f 100644
--- a/harper-core/src/parsers/collapse_identifiers.rs
+++ b/harper-core/src/parsers/collapse_identifiers.rs
@@ -4,7 +4,7 @@ use std::sync::Arc;
use itertools::Itertools;
use super::Parser;
-use crate::patterns::{PatternExt, SequencePattern};
+use crate::expr::{ExprExt, SequenceExpr};
use crate::{Dictionary, Lrc, Span, Token, TokenKind, VecExt};
/// A parser that wraps any other parser to collapse token strings that match
@@ -24,9 +24,9 @@ impl CollapseIdentifiers {
}
thread_local! {
- static WORD_OR_NUMBER: Lrc<SequencePattern> = Lrc::new(SequencePattern::default()
+ static WORD_OR_NUMBER: Lrc<SequenceExpr> = Lrc::new(SequenceExpr::default()
.then_any_word()
- .then_one_or_more(SequencePattern::default()
+ .then_one_or_more(SequenceExpr::default()
.then_case_separator()
.then_any_word()));
}
@@ -39,7 +39,8 @@ impl Parser for CollapseIdentifiers {
for tok_span in WORD_OR_NUMBER
.with(|v| v.clone())
- .find_all_matches(&tokens, source)
+ .iter_matches(&tokens, source)
+ .collect::<Vec<_>>()
{
let start_tok = &tokens[tok_span.start];
let end_tok = &tokens[tok_span.end - 1];
@@ -73,8 +74,8 @@ mod tests {
assert_eq!(
WORD_OR_NUMBER
.with(|v| v.clone())
- .find_all_matches(&PlainEnglish.parse(&source), &source)
- .len(),
+ .iter_matches(&PlainEnglish.parse(&source), &source)
+ .count(),
1
);
}
diff --git a/harper-core/src/patterns/all.rs b/harper-core/src/patterns/all.rs
deleted file mode 100644
index 648833aee..000000000
--- a/harper-core/src/patterns/all.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-use crate::Token;
-
-use super::Pattern;
-
-/// A [`Pattern`] that consumes a list of other patterns and only
-/// matches if all the child patterns do.
-///
-/// It will match the length of the longest pattern.
-#[derive(Default)]
-pub struct All {
- children: Vec<Box<dyn Pattern>>,
-}
-
-impl All {
- pub fn new(children: Vec<Box<dyn Pattern>>) -> Self {
- Self { children }
- }
-
- pub fn add(&mut self, p: Box<dyn Pattern>) {
- self.children.push(p);
- }
-}
-
-impl Pattern for All {
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
- let mut max = 0;
-
- for pattern in &self.children {
- let len = pattern.matches(tokens, source)?;
- max = max.max(len);
- }
-
- Some(max)
- }
-}
diff --git a/harper-core/src/patterns/first_match_of.rs b/harper-core/src/patterns/first_match_of.rs
deleted file mode 100644
index 5f5fdea07..000000000
--- a/harper-core/src/patterns/first_match_of.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use super::Pattern;
-use crate::Token;
-
-/// A naive pattern collection that naively iterates through a list of patterns,
-/// returning the first one that matches.
-///
-/// Compare to [`LongestMatchOf`](super::LongestMatchOf), which returns the longest match.
-#[derive(Default)]
-pub struct FirstMatchOf {
- patterns: Vec<Box<dyn Pattern>>,
-}
-
-impl FirstMatchOf {
- pub fn push(&mut self, pattern: Box<dyn Pattern>) {
- self.patterns.push(pattern);
- }
-}
-
-impl Pattern for FirstMatchOf {
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
- self.patterns
- .iter()
- .filter_map(|p| p.matches(tokens, source))
- .next()
- }
-}
diff --git a/harper-core/src/patterns/longest_match_of.rs b/harper-core/src/patterns/longest_match_of.rs
deleted file mode 100644
index d5fc7896e..000000000
--- a/harper-core/src/patterns/longest_match_of.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use crate::Token;
-
-use super::Pattern;
-
-/// A pattern that returns the value of the longest match in a list.
-#[derive(Default)]
-pub struct LongestMatchOf {
- patterns: Vec<Box<dyn Pattern>>,
-}
-
-impl LongestMatchOf {
- pub fn new(patterns: Vec<Box<dyn Pattern>>) -> Self {
- Self { patterns }
- }
-
- pub fn add(&mut self, pattern: Box<dyn Pattern>) {
- self.patterns.push(pattern);
- }
-}
-
-impl Pattern for LongestMatchOf {
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
- let mut longest = None;
-
- for pattern in self.patterns.iter() {
- let Some(match_len) = pattern.matches(tokens, source) else {
- continue;
- };
-
- if let Some(longest_len) = longest {
- if match_len > longest_len {
- longest = Some(match_len);
- }
- } else {
- longest = Some(match_len);
- }
- }
-
- longest
- }
-}
diff --git a/harper-core/src/patterns/mod.rs b/harper-core/src/patterns/mod.rs
index 9183a286a..ef67bcfd2 100644
--- a/harper-core/src/patterns/mod.rs
+++ b/harper-core/src/patterns/mod.rs
@@ -7,54 +7,28 @@
use crate::{Document, LSend, Span, Token};
-mod all;
mod any_pattern;
-mod first_match_of;
-mod fixed_phrase;
mod implies_quantity;
mod indefinite_article;
mod inflection_of_be;
mod invert;
-mod longest_match_of;
-mod mergeable_words;
mod nominal_phrase;
-mod pattern_map;
-mod repeating_pattern;
-mod sequence_pattern;
-mod similar_to_phrase;
-mod spelled_number_pattern;
-mod time_unit_pattern;
mod whitespace_pattern;
mod within_edit_distance;
mod word;
-mod word_pattern_group;
mod word_set;
-pub use all::All;
pub use any_pattern::AnyPattern;
-use blanket::blanket;
-pub use first_match_of::FirstMatchOf;
-pub use fixed_phrase::FixedPhrase;
pub use implies_quantity::ImpliesQuantity;
pub use indefinite_article::IndefiniteArticle;
pub use inflection_of_be::InflectionOfBe;
pub use invert::Invert;
-pub use longest_match_of::LongestMatchOf;
-pub use mergeable_words::MergeableWords;
pub use nominal_phrase::NominalPhrase;
-pub use pattern_map::PatternMap;
-pub use repeating_pattern::RepeatingPattern;
-pub use sequence_pattern::SequencePattern;
-pub use similar_to_phrase::SimilarToPhrase;
-pub use spelled_number_pattern::SpelledNumberPattern;
-pub use time_unit_pattern::TimeUnitPattern;
pub use whitespace_pattern::WhitespacePattern;
+pub use within_edit_distance::WithinEditDistance;
pub use word::Word;
-pub use word_pattern_group::WordPatternGroup;
pub use word_set::WordSet;
-#[cfg_attr(feature = "concurrent", blanket(derive(Arc)))]
-#[cfg_attr(not(feature = "concurrent"), blanket(derive(Rc, Arc)))]
pub trait Pattern: LSend {
/// Check if the pattern matches at the start of the given token slice.
///
@@ -123,19 +97,6 @@ where
}
}
-pub trait OwnedPatternExt {
- fn or(self, other: impl Pattern + 'static) -> LongestMatchOf;
-}
-
-impl<P> OwnedPatternExt for P
-where
- P: Pattern + 'static,
-{
- fn or(self, other: impl Pattern + 'static) -> LongestMatchOf {
- LongestMatchOf::new(vec![Box::new(self), Box::new(other)])
- }
-}
-
/// A simpler version of the [`Pattern`] trait that only matches a single
/// token.
pub trait SingleTokenPattern: LSend {
diff --git a/harper-core/src/patterns/repeating_pattern.rs b/harper-core/src/patterns/repeating_pattern.rs
deleted file mode 100644
index b18aa2eef..000000000
--- a/harper-core/src/patterns/repeating_pattern.rs
+++ /dev/null
@@ -1,75 +0,0 @@
-use super::Pattern;
-use crate::Token;
-
-/// A pattern that will match one or more repetitions of the same pattern.
-///
-/// Somewhat reminiscent of the `.*` operator in Regex.
-pub struct RepeatingPattern {
- inner: Box<dyn Pattern>,
- required_repetitions: usize,
-}
-
-impl RepeatingPattern {
- pub fn new(pattern: Box<dyn Pattern>, required_repetitions: usize) -> Self {
- Self {
- inner: pattern,
- required_repetitions,
- }
- }
-}
-
-impl Pattern for RepeatingPattern {
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
- let mut tok_cursor = 0;
- let mut repetition = 0;
-
- loop {
- let match_len = self.inner.matches(&tokens[tok_cursor..], source);
-
- if let Some(match_len) = match_len {
- if match_len == 0 {
- // If match_len == 0, we won't move forward ever again.
- // This means that we can get infinitely many repetitions,
- // so repetition >= self.required_repetitions is guaranteed.
- return Some(tok_cursor);
- }
-
- tok_cursor += match_len;
- repetition += 1;
- } else if repetition >= self.required_repetitions {
- return Some(tok_cursor);
- } else {
- return None;
- }
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
-
- use super::RepeatingPattern;
- use crate::Document;
- use crate::patterns::{AnyPattern, Pattern};
-
- #[test]
- fn matches_anything() {
- let doc = Document::new_plain_english_curated(
- "This matcher will match the entirety of any document!",
- );
- let pat = RepeatingPattern::new(Box::new(AnyPattern), 0);
-
- assert_eq!(
- pat.matches(doc.get_tokens(), doc.get_source()),
- Some(doc.get_tokens().len())
- )
- }
-
- #[test]
- fn does_not_match_short() {
- let doc = Document::new_plain_english_curated("No match");
- let pat = RepeatingPattern::new(Box::new(AnyPattern), 4);
-
- assert_eq!(pat.matches(doc.get_tokens(), doc.get_source()), None)
- }
-}
diff --git a/harper-core/src/patterns/sequence_pattern.rs b/harper-core/src/patterns/sequence_pattern.rs
deleted file mode 100644
index e5029b6df..000000000
--- a/harper-core/src/patterns/sequence_pattern.rs
+++ /dev/null
@@ -1,256 +0,0 @@
-use paste::paste;
-
-use super::whitespace_pattern::WhitespacePattern;
-use super::{AnyPattern, IndefiniteArticle, Pattern, RepeatingPattern, Word};
-use crate::{Token, TokenKind};
-
-/// A pattern that checks that a sequence of other patterns match.
-/// There are specific extension methods available, but you can also use [`Self::then`] to add
-/// arbitrary patterns.
-///
-/// ## Example
-///
-/// Let's say we wanted to locate places in a [`Document`](crate::Document) where an article is followed by a noun.
-/// We can do that with a `SequencePattern`.
-///
-/// ```rust
-/// use harper_core::patterns::{SequencePattern, DocPattern};
-/// use harper_core::{Document, Span};
-///
-/// let document = Document::new_markdown_default_curated("This is a test.");
-///
-/// let pattern = SequencePattern::default().then_determiner().then_whitespace().then_nominal();
-/// let matches = pattern.find_all_matches_in_doc(&document);
-///
-/// // The pattern found that the tokens at indexes 4, 5, and 6 fit the criteria.
-/// assert_eq!(matches, vec![Span::new(4, 7)]);
-/// ```
-#[derive(Default)]
-pub struct SequencePattern {
- token_patterns: Vec<Box<dyn Pattern>>,
-}
-
-/// Generate a `then_*` method from an available `is_*` function on [`TokenKind`].
-macro_rules! gen_then_from_is {
- ($quality:ident) => {
- paste! {
- pub fn [< then_$quality >] (mut self) -> Self{
- self.token_patterns.push(Box::new(|tok: &Token, _source: &[char]| {
- tok.kind.[< is_$quality >]()
- }));
-
- self
- }
-
- pub fn [< then_one_or_more_$quality s >] (self) -> Self{
- self.then_one_or_more(Box::new(|tok: &Token, _source: &[char]| {
- tok.kind.[< is_$quality >]()
- }))
- }
-
- pub fn [< then_anything_but_$quality >] (mut self) -> Self{
- self.token_patterns.push(Box::new(|tok: &Token, _source: &[char]| {
- if tok.kind.[< is_$quality >](){
- false
- }else{
- true
- }
- }));
-
- self
- }
- }
- };
-}
-
-impl SequencePattern {
- gen_then_from_is!(nominal);
- gen_then_from_is!(noun);
- gen_then_from_is!(possessive_nominal);
- gen_then_from_is!(plural_nominal);
- gen_then_from_is!(verb);
- gen_then_from_is!(auxiliary_verb);
- gen_then_from_is!(linking_verb);
- gen_then_from_is!(pronoun);
- gen_then_from_is!(punctuation);
- gen_then_from_is!(conjunction);
- gen_then_from_is!(comma);
- gen_then_from_is!(period);
- gen_then_from_is!(number);
- gen_then_from_is!(case_separator);
- gen_then_from_is!(adverb);
- gen_then_from_is!(adjective);
- gen_then_from_is!(apostrophe);
- gen_then_from_is!(hyphen);
- gen_then_from_is!(determiner);
- gen_then_from_is!(proper_noun);
- gen_then_from_is!(preposition);
- gen_then_from_is!(not_plural_nominal);
-
- pub fn then_indefinite_article(self) -> Self {
- self.then(IndefiniteArticle::default())
- }
-
- /// Match examples of `word` case-sensitively.
- pub fn then_exact_word(mut self, word: &'static str) -> Self {
- self.token_patterns.push(Box::new(Word::new_exact(word)));
- self
- }
-
- /// Shorthand for [`Self::any_capitalization_of`].
- pub fn aco(word: &'static str) -> Self {
- Self::any_capitalization_of(word)
- }
-
- pub fn any_capitalization_of(word: &'static str) -> Self {
- Self::default().then_any_capitalization_of(word)
- }
-
- /// Shorthand for [`Self::then_any_capitalization_of`].
- pub fn t_aco(self, word: &'static str) -> Self {
- self.then_any_capitalization_of(word)
- }
-
- /// Match examples of `word` that have any capitalization.
- pub fn then_any_capitalization_of(mut self, word: &'static str) -> Self {
- self.token_patterns.push(Box::new(Word::new(word)));
- self
- }
-
- /// Matches any word.
- pub fn then_any_word(mut self) -> Self {
- self.token_patterns
- .push(Box::new(|tok: &Token, _source: &[char]| tok.kind.is_word()));
- self
- }
-
- /// Matches any token whose `Kind` exactly matches.
- pub fn then_strict(mut self, kind: TokenKind) -> Self {
- self.token_patterns
- .push(Box::new(move |tok: &Token, _source: &[char]| {
- tok.kind == kind
- }));
- self
- }
-
- /// Shorthand for [`Self::then_whitespace`].
- pub fn t_ws(self) -> Self {
- self.then_whitespace()
- }
-
- /// Match against one or more whitespace tokens.
- pub fn then_whitespace(mut self) -> Self {
- self.token_patterns.push(Box::new(WhitespacePattern));
- self
- }
-
- pub fn then_one_or_more(mut self, pat: impl Pattern + 'static) -> Self {
- self.token_patterns
- .push(Box::new(RepeatingPattern::new(Box::new(pat), 1)));
- self
- }
-
- /// Shorthand for [`Self::then_anything`].
- pub fn t_any(self) -> Self {
- self.then_anything()
- }
-
- /// Match against any single token.
- /// More of a filler than anything else.
- pub fn then_anything(mut self) -> Self {
- self.token_patterns.push(Box::new(AnyPattern));
- self
- }
-
- pub fn then(mut self, pat: impl Pattern + 'static) -> Self {
- self.token_patterns.push(Box::new(pat));
- self
- }
-}
-
-impl Pattern for SequencePattern {
- fn matches(&self, tokens: &[Token], source: &[char]) -> Option<usize> {
- let mut tok_cursor = 0;
-
- for pat in self.token_patterns.iter() {
- let match_length = pat.matches(&tokens[tok_cursor..], source)?;
- tok_cursor += match_length;
- }
-
- Some(tok_cursor)
- }
-}
-
-#[cfg(test)]
-mod tests {
-
- use super::SequencePattern;
- use crate::Document;
- use crate::patterns::{DocPattern, Pattern};
-
- #[test]
- fn matches_n_whitespace_tokens() {
- let pat = SequencePattern::default()
- .then_any_word()
- .then_whitespace()
- .then_any_word();
- let doc = Document::new_plain_english_curated("word\n \nword");
-
- assert_eq!(
- pat.matches(doc.get_tokens(), doc.get_source()),
- Some(doc.get_tokens().len())
- );
- }
-
- #[test]
- fn matches_specific_words() {
- let pat = SequencePattern::default()
- .then_exact_word("she")
- .then_whitespace()
- .then_exact_word("her");
- let doc = Document::new_plain_english_curated("she her");
-
- assert_eq!(
- pat.matches(doc.get_tokens(), doc.get_source()),
- Some(doc.get_tokens().len())
- );
- }
-
- #[test]
- fn match_t_aco_and_t_ws() {
- let pat = SequencePattern::aco("foo").t_ws().t_aco("bar");
- let doc = Document::new_plain_english_curated("foo\nBAR");
-
- assert_eq!(
- pat.matches(doc.get_tokens(), doc.get_source()),
- Some(doc.get_tokens().len())
- );
- }
-
- #[test]
- fn exact_word_matches_title_case() {
- let pat = SequencePattern::default().then_exact_word("Foo");
- let doc = Document::new_plain_english_curated("Foo");
-
- assert_eq!(
- pat.matches(doc.get_tokens(), doc.get_source()),
- Some(doc.get_tokens().len())
- );
- }
-
- #[test]
- fn exact_means_case_sensitive() {
- let pat = SequencePattern::default().then_exact_word("Foo");
- let doc = Document::new_plain_english_curated("foo Foo FOO");
- let matches = pat.find_all_matches_in_doc(&doc);
- assert_eq!(matches.len(), 1); // Only "Foo" should match
- }
-
- #[test]
- fn any_capitalization_of_matches_different_cases() {
- let pat = SequencePattern::aco("foo");
- let doc = Document::new_plain_english_curated("foo Foo FOO");
- let matches = pat.find_all_matches_in_doc(&doc);
- assert_eq!(matches.len(), 3); // All three should match
- }
-}
diff --git a/harper-core/src/patterns/word_pattern_group.rs b/harper-core/src/patterns/word_pattern_group.rs
deleted file mode 100644
index 54c4aa7c5..000000000
--- a/harper-core/src/patterns/word_pattern_group.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-use hashbrown::HashMap;
-
-use super::first_match_of::FirstMatchOf;
-use super::{Pattern, SequencePattern};
-use crate::CharString;
-
-/// A pattern collection to look for patterns that start with a specific
-/// word.
-#[derive(Default)]
-pub struct WordPatternGroup<P>
-where
- P: Pattern,
-{
- patterns: HashMap<CharString, P>,
-}
-
-impl WordPatternGroup<FirstMatchOf> {
- pub fn add(&mut self, word: &str, pat: Box<dyn Pattern>) {
- let chars = word.chars().collect();
-
- if let Some(group) = self.patterns.get_mut(&chars) {
- group.push(pat);
- } else {
- let mut group = FirstMatchOf::default();
- group.push(pat);
- self.patterns.insert(chars, group);
- }
- }
-
- /// Add a pattern that matches just a word on its own, without anything else required to match.
- pub fn add_word(&mut self, word: &'static str) {
- self.add(
- word,
- Box::new(SequencePattern::default().then_exact_word(word)),
- );
- }
-}
-
-impl<P> Pattern for WordPatternGroup<P>
-where
- P: Pattern,
-{
- fn matches(&self, tokens: &[crate::Token], source: &[char]) -> Option<usize> {
- let first = tokens.first()?;
- if !first.kind.is_word() {
- return None;
- }
-
- let word_chars = first.span.get_content(source);
- let inner_pattern = self.patterns.get(word_chars)?;
-
- inner_pattern.matches(tokens, source)
- }
-}
diff --git a/harper-core/src/span.rs b/harper-core/src/span.rs
index d1603d716..4c93f9891 100644
--- a/harper-core/src/span.rs
+++ b/harper-core/src/span.rs
@@ -59,6 +59,18 @@ impl Span {
Some(&source[self.start..self.end])
}
+ /// Expand the span by either modifying [`Self::start`] or [`Self::end`] to include the target
+ /// index.
+ ///
+ /// Does nothing if the span already includes the target.
+ pub fn expand_to_include(&mut self, target: usize) {
+ if target < self.start {
+ self.start = target;
+ } else if target >= self.end {
+ self.end = target + 1;
+ }
+ }
+
/// Get the associated content. Will panic if any aspect is invalid.
pub fn get_content<'a>(&self, source: &'a [char]) -> &'a [char] {
match self.try_get_content(source) {
@@ -160,4 +172,15 @@ mod tests {
assert!(!Span::new(0, 3).overlaps_with(Span::new(3, 5)));
}
+
+ #[test]
+ fn expands_properly() {
+ let mut span = Span::new(2, 2);
+
+ span.expand_to_include(1);
+ assert_eq!(span, Span::new(1, 2));
+
+ span.expand_to_include(2);
+ assert_eq!(span, Span::new(1, 3));
+ }
}
diff --git a/harper-core/src/token_string_ext.rs b/harper-core/src/token_string_ext.rs
index 2ff2a1073..91abc782b 100644
--- a/harper-core/src/token_string_ext.rs
+++ b/harper-core/src/token_string_ext.rs
@@ -11,7 +11,7 @@ macro_rules! create_decl_for {
fn [< last_ $thing _index >](&self) -> Option<usize>;
- fn [<iter_ $thing _indices>](&self) -> impl Iterator<Item = usize> + '_;
+ fn [<iter_ $thing _indices>](&self) -> impl DoubleEndedIterator<Item = usize> + '_;
fn [<iter_ $thing s>](&self) -> impl Iterator<Item = &Token> + '_;
}
@@ -33,7 +33,7 @@ macro_rules! create_fns_for {
self.iter().rev().position(|v| v.kind.[<is_ $thing>]()).map(|i| self.len() - i - 1)
}
- fn [<iter_ $thing _indices>](&self) -> impl Iterator<Item = usize> + '_ {
+ fn [<iter_ $thing _indices>](&self) -> impl DoubleEndedIterator<Item = usize> + '_ {
self.iter()
.enumerate()
.filter(|(_, t)| t.kind.[<is_ $thing>]())
diff --git a/packages/web/src/routes/docs/contributors/author-a-rule/+page.md b/packages/web/src/routes/docs/contributors/author-a-rule/+page.md
index 2d34212b8..5228652cc 100644
--- a/packages/web/src/routes/docs/contributors/author-a-rule/+page.md
+++ b/packages/web/src/routes/docs/contributors/author-a-rule/+page.md
@@ -120,18 +120,18 @@ Finally, enable it in a macro invocation near the bottom:
```rust title="harper-core/src/linting/lint_group.rs"
insert_struct_rule!(AdjectiveOfA, true);
-insert_pattern_rule!(BackInTheDay, true);
+insert_expr_rule!(BackInTheDay, true);
insert_struct_rule!(WordPressDotcom, true);
-insert_pattern_rule!(OutOfDate, true);
-// [svp! df:+] insert_pattern_rule!(MyRule, true);
+insert_expr_rule!(OutOfDate, true);
+// [svp! df:+] insert_expr_rule!(MyRule, true);
```
-If you use a `PatternLinter`, use `insert_pattern_rule` to take advantage of Harper's aggressive caching.
+If you use a `ExprLinter`, use `insert_expr_rule` to take advantage of Harper's aggressive caching.
Otherwise, use `insert_struct_rule`.
## Write Your Rule
-Defining a pattern and [implementing the PatternLinter trait](https://docs.rs/harper-core/latest/harper_core/linting/trait.PatternLinter.html) is the easiest way to define a new rule for Harper.
+Defining an expression and [implementing the ExprLinter trait](https://docs.rs/harper-core/latest/harper_core/linting/trait.ExprLinter.html) is the easiest way to define a new rule for Harper.
Here's a template to get you started:
```rust title="my_rule.rs"
@@ -139,30 +139,30 @@ use crate::{
Lrc, Token
};
-use super::{Lint, PatternLinter};
+use super::{Lint, ExprLinter};
pub struct MyRule {
- pattern: Box<dyn Pattern>,
+ expr: Box<dyn Expr>,
}
impl Default for MyRule {
fn default() -> Self {
- // Define the grammatical pattern the rule should look for in user text.
- let mut pattern = todo!();
+ // Define the grammatical expr the rule should look for in user text.
+ let mut expr = todo!();
Self {
- pattern: Box::new(pattern),
+ expr: Box::new(expr),
}
}
}
-impl PatternLinter for ThatWhich {
- /// Pass the pattern to the PatternLinter framework.
- fn pattern(&self) -> &dyn Pattern {
- self.pattern.as_ref()
+impl ExprLinter for ThatWhich {
+ /// Pass the expr to the ExprLinter framework.
+ fn expr(&self) -> &dyn Expr {
+ self.expr.as_ref()
}
- /// Any series of tokens that match the pattern provided in the `default()` method above will
+ /// Any series of tokens that match the expr provided in the `default()` method above will
/// be provided to this function, which you are required to map into a [`Lint`] object.
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
unimplemented!();