harper_core/expr/
sequence_expr.rs

1use paste::paste;
2
3use crate::{
4    CharStringExt, Span, Token, TokenKind,
5    expr::{FirstMatchOf, LongestMatchOf},
6    patterns::{AnyPattern, IndefiniteArticle, WhitespacePattern, Word, WordSet},
7};
8
9use super::{Expr, Optional, Repeating, Step, UnlessStep};
10
11#[derive(Default)]
12pub struct SequenceExpr {
13    exprs: Vec<Box<dyn Expr>>,
14}
15
16/// Generate a `then_*` method from an available `is_*` function on [`TokenKind`].
17macro_rules! gen_then_from_is {
18    ($quality:ident) => {
19        paste! {
20            #[doc = concat!("Adds a step matching a token where [`TokenKind::is_", stringify!($quality), "()`] returns true.")]
21            pub fn [< then_$quality >] (self) -> Self{
22                self.then(|tok: &Token, _source: &[char]| {
23                    tok.kind.[< is_$quality >]()
24                })
25            }
26
27            #[doc = concat!("Adds an optional step matching a token where [`TokenKind::is_", stringify!($quality), "()`] returns true.")]
28            pub fn [< then_optional_$quality >] (self) -> Self{
29                self.then_optional(|tok: &Token, _source: &[char]| {
30                    tok.kind.[< is_$quality >]()
31                })
32            }
33
34            #[doc = concat!("Adds a step matching one or more consecutive tokens where [`TokenKind::is_", stringify!($quality), "()`] returns true.")]
35            pub fn [< then_one_or_more_$quality s >] (self) -> Self{
36                self.then_one_or_more(Box::new(|tok: &Token, _source: &[char]| {
37                    tok.kind.[< is_$quality >]()
38                }))
39            }
40
41            #[doc = concat!("Adds a step matching a token where [`TokenKind::is_", stringify!($quality), "()`] returns false.")]
42            pub fn [< then_anything_but_$quality >] (self) -> Self{
43                self.then(|tok: &Token, _source: &[char]| {
44                    if tok.kind.[< is_$quality >](){
45                        false
46                    }else{
47                        true
48                    }
49                })
50            }
51        }
52    };
53}
54
55impl Expr for SequenceExpr {
56    /// Run the expression starting at an index, returning the total matched window.
57    ///
58    /// If any step returns `None`, the entire expression does as well.
59    fn run(&self, mut cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span<Token>> {
60        let mut window = Span::new_with_len(cursor, 0);
61
62        for cur_expr in &self.exprs {
63            let out = cur_expr.run(cursor, tokens, source)?;
64
65            // Only expand the window if the match actually covers some tokens
66            if out.end > out.start {
67                window.expand_to_include(out.start);
68                window.expand_to_include(out.end.checked_sub(1).unwrap_or(out.start));
69            }
70
71            // Only advance cursor if we actually matched something
72            if out.end > cursor {
73                cursor = out.end;
74            } else if out.start < cursor {
75                cursor = out.start;
76            }
77            // If both start and end are equal to cursor, don't move the cursor
78        }
79
80        Some(window)
81    }
82}
83
84impl SequenceExpr {
85    // Constructor methods
86
87    /// Construct a new sequence with a [`Word`] at the beginning of the operation list.
88    pub fn any_capitalization_of(word: &'static str) -> Self {
89        Self::default().then_any_capitalization_of(word)
90    }
91
92    /// Shorthand for [`Self::any_capitalization_of`].
93    pub fn aco(word: &'static str) -> Self {
94        Self::any_capitalization_of(word)
95    }
96
97    /// Match any word from the given set of words, case-insensitive.
98    pub fn word_set(words: &'static [&'static str]) -> Self {
99        Self::default().then_word_set(words)
100    }
101
102    // General builder methods
103
104    /// Push an [expression](Expr) to the operation list.
105    pub fn then(mut self, expr: impl Expr + 'static) -> Self {
106        self.exprs.push(Box::new(expr));
107        self
108    }
109
110    /// Pushes an expression that could move the cursor to the sequence, but does not require it.
111    pub fn then_optional(mut self, expr: impl Expr + 'static) -> Self {
112        self.exprs.push(Box::new(Optional::new(expr)));
113        self
114    }
115
116    /// Pushes an expression that will match any of the provided expressions.
117    ///
118    /// If more than one of the provided expressions match, this function provides no guarantee
119    /// as to which match will end up being used. If you need to get the longest of multiple
120    /// matches, use [`Self::then_longest_of()`] instead.
121    pub fn then_any_of(mut self, exprs: Vec<Box<dyn Expr>>) -> Self {
122        self.exprs.push(Box::new(FirstMatchOf::new(exprs)));
123        self
124    }
125
126    /// Pushes an expression that will match the longest of the provided expressions.
127    ///
128    /// If you don't need the longest match, prefer using the short-circuiting
129    /// [`Self::then_any_of()`] instead.
130    pub fn then_longest_of(mut self, exprs: Vec<Box<dyn Expr>>) -> Self {
131        self.exprs.push(Box::new(LongestMatchOf::new(exprs)));
132        self
133    }
134
135    /// Appends the steps in `other` onto the end of `self`.
136    /// This is more efficient than [`Self::then`] because it avoids pointer redirection.
137    pub fn then_seq(mut self, mut other: Self) -> Self {
138        self.exprs.append(&mut other.exprs);
139        self
140    }
141
142    /// Pushes an expression that will match any word from the given set of words, case-insensitive.
143    pub fn then_word_set(self, words: &'static [&'static str]) -> Self {
144        self.then(WordSet::new(words))
145    }
146
147    /// Matches any token whose `Kind` exactly matches.
148    pub fn then_strict(self, kind: TokenKind) -> Self {
149        self.then(move |tok: &Token, _source: &[char]| tok.kind == kind)
150    }
151
152    /// Match against one or more whitespace tokens.
153    pub fn then_whitespace(self) -> Self {
154        self.then(WhitespacePattern)
155    }
156
157    /// Shorthand for [`Self::then_whitespace`].
158    pub fn t_ws(self) -> Self {
159        self.then_whitespace()
160    }
161
162    pub fn then_one_or_more(self, expr: impl Expr + 'static) -> Self {
163        self.then(Repeating::new(Box::new(expr), 1))
164    }
165
166    /// Create a new condition that will step one token forward if met.
167    /// If the condition is _not_ met, the whole expression returns `None`.
168    ///
169    /// This can be used to build out exceptions to other rules.
170    ///
171    /// See [`UnlessStep`] for more info.
172    pub fn then_unless(self, condition: impl Expr + 'static) -> Self {
173        self.then(UnlessStep::new(condition, |_tok: &Token, _src: &[char]| {
174            true
175        }))
176    }
177
178    /// Match any single token.
179    ///
180    /// See [`AnyPattern`] for more info.
181    pub fn then_anything(self) -> Self {
182        self.then(AnyPattern)
183    }
184
185    /// Match any single token.
186    ///
187    /// Shorthand for [`Self::then_anything`].
188    pub fn t_any(self) -> Self {
189        self.then_anything()
190    }
191
192    // Word matching methods
193
194    /// Matches any word.
195    pub fn then_any_word(self) -> Self {
196        self.then(|tok: &Token, _source: &[char]| tok.kind.is_word())
197    }
198
199    /// Match examples of `word` that have any capitalization.
200    pub fn then_any_capitalization_of(self, word: &'static str) -> Self {
201        self.then(Word::new(word))
202    }
203
204    /// Shorthand for [`Self::then_any_capitalization_of`].
205    pub fn t_aco(self, word: &'static str) -> Self {
206        self.then_any_capitalization_of(word)
207    }
208
209    /// Match examples of `word` case-sensitively.
210    pub fn then_exact_word(self, word: &'static str) -> Self {
211        self.then(Word::new_exact(word))
212    }
213
214    /// Match any word except the ones in `words`.
215    pub fn then_word_except(self, words: &'static [&'static str]) -> Self {
216        self.then(move |tok: &Token, src: &[char]| {
217            !tok.kind.is_word()
218                || !words
219                    .iter()
220                    .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
221        })
222    }
223
224    /// Match a token of a given kind which is not in the list of words.
225    pub fn then_kind_except<F>(self, pred: F, words: &'static [&'static str]) -> Self
226    where
227        F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
228    {
229        self.then(move |tok: &Token, src: &[char]| {
230            pred(&tok.kind)
231                && !words
232                    .iter()
233                    .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
234        })
235    }
236
237    /// Adds a step matching a token where both token kind predicates return true.
238    pub fn then_kind_both<F1, F2>(self, pred1: F1, pred2: F2) -> Self
239    where
240        F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
241        F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
242    {
243        self.then(move |tok: &Token, _source: &[char]| pred1(&tok.kind) && pred2(&tok.kind))
244    }
245
246    /// Adds a step matching a token where either of the two token kind predicates returns true.
247    pub fn then_kind_either<F1, F2>(self, pred1: F1, pred2: F2) -> Self
248    where
249        F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
250        F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
251    {
252        self.then(move |tok: &Token, _source: &[char]| pred1(&tok.kind) || pred2(&tok.kind))
253    }
254
255    /// Adds a step matching a token where any of the token kind predicates returns true.
256    pub fn then_kind_any<F>(self, preds: &'static [F]) -> Self
257    where
258        F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
259    {
260        self.then(move |tok: &Token, _source: &[char]| preds.iter().any(|pred| pred(&tok.kind)))
261    }
262
263    /// Adds a step matching a token where the first token kind predicate returns true and the second returns false.
264    pub fn then_kind_is_but_is_not<F1, F2>(self, pred1: F1, pred2: F2) -> Self
265    where
266        F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
267        F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
268    {
269        self.then(move |tok: &Token, _source: &[char]| pred1(&tok.kind) && !pred2(&tok.kind))
270    }
271
272    /// Adds a step matching a token where the first token kind predicate returns true and the second returns false,
273    /// and the token is not in the list of words.
274    pub fn then_kind_is_but_is_not_except<F1, F2>(
275        self,
276        pred1: F1,
277        pred2: F2,
278        words: &'static [&'static str],
279    ) -> Self
280    where
281        F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
282        F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
283    {
284        self.then(move |tok: &Token, src: &[char]| {
285            pred1(&tok.kind)
286                && !pred2(&tok.kind)
287                && !words
288                    .iter()
289                    .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
290        })
291    }
292
293    // Out-of-vocabulary word. (Words not in the dictionary)
294    gen_then_from_is!(oov);
295
296    // Part-of-speech matching methods
297
298    // Nominals (nouns and pronouns)
299
300    gen_then_from_is!(nominal);
301    gen_then_from_is!(plural_nominal);
302    gen_then_from_is!(non_plural_nominal);
303    gen_then_from_is!(possessive_nominal);
304
305    // Nouns
306
307    gen_then_from_is!(noun);
308    gen_then_from_is!(proper_noun);
309    gen_then_from_is!(mass_noun_only);
310
311    // Pronouns
312
313    gen_then_from_is!(pronoun);
314    gen_then_from_is!(first_person_singular_pronoun);
315    gen_then_from_is!(first_person_plural_pronoun);
316    gen_then_from_is!(second_person_pronoun);
317    gen_then_from_is!(third_person_pronoun);
318    gen_then_from_is!(third_person_singular_pronoun);
319    gen_then_from_is!(third_person_plural_pronoun);
320    gen_then_from_is!(object_pronoun);
321
322    // Verbs
323
324    gen_then_from_is!(verb);
325    gen_then_from_is!(auxiliary_verb);
326    gen_then_from_is!(linking_verb);
327
328    // Adjectives
329
330    gen_then_from_is!(adjective);
331    gen_then_from_is!(positive_adjective);
332    gen_then_from_is!(comparative_adjective);
333
334    // Adverbs
335
336    gen_then_from_is!(adverb);
337
338    // Determiners
339
340    gen_then_from_is!(determiner);
341    gen_then_from_is!(demonstrative_determiner);
342    gen_then_from_is!(quantifier);
343    gen_then_from_is!(non_quantifier_determiner);
344
345    /// Push an [`IndefiniteArticle`] to the end of the operation list.
346    pub fn then_indefinite_article(self) -> Self {
347        self.then(IndefiniteArticle::default())
348    }
349
350    // Other parts of speech
351
352    gen_then_from_is!(conjunction);
353    gen_then_from_is!(preposition);
354
355    // Punctuation
356
357    gen_then_from_is!(punctuation);
358    gen_then_from_is!(apostrophe);
359    gen_then_from_is!(comma);
360    gen_then_from_is!(hyphen);
361    gen_then_from_is!(period);
362    gen_then_from_is!(semicolon);
363
364    // Other
365
366    gen_then_from_is!(number);
367    gen_then_from_is!(case_separator);
368    gen_then_from_is!(likely_homograph);
369}
370
371impl<S> From<S> for SequenceExpr
372where
373    S: Step + 'static,
374{
375    fn from(step: S) -> Self {
376        Self {
377            exprs: vec![Box::new(step)],
378        }
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use crate::{
385        Document, TokenKind,
386        expr::{ExprExt, SequenceExpr},
387        linting::tests::SpanVecExt,
388    };
389
390    #[test]
391    fn test_kind_both() {
392        let noun_and_verb =
393            SequenceExpr::default().then_kind_both(TokenKind::is_noun, TokenKind::is_verb);
394        let doc = Document::new_plain_english_curated("Use a good example.");
395        let matches = noun_and_verb.iter_matches_in_doc(&doc).collect::<Vec<_>>();
396        assert_eq!(matches.to_strings(&doc), vec!["Use", "good", "example"]);
397    }
398
399    #[test]
400    fn test_adjective_or_determiner() {
401        let expr = SequenceExpr::default()
402            .then_kind_either(TokenKind::is_adjective, TokenKind::is_determiner);
403        let doc = Document::new_plain_english_curated("Use a good example.");
404        let matches = expr.iter_matches_in_doc(&doc).collect::<Vec<_>>();
405        assert_eq!(matches.to_strings(&doc), vec!["a", "good"]);
406    }
407
408    #[test]
409    fn test_noun_but_not_adjective() {
410        let expr = SequenceExpr::default()
411            .then_kind_is_but_is_not(TokenKind::is_noun, TokenKind::is_adjective);
412        let doc = Document::new_plain_english_curated("Use a good example.");
413        let matches = expr.iter_matches_in_doc(&doc).collect::<Vec<_>>();
414        assert_eq!(matches.to_strings(&doc), vec!["Use", "example"]);
415    }
416}