harper_core/expr/
sequence_expr.rs

1use paste::paste;
2
3use crate::{
4    CharStringExt, Span, Token, TokenKind,
5    expr::{FirstMatchOf, FixedPhrase, LongestMatchOf},
6    patterns::{AnyPattern, IndefiniteArticle, WhitespacePattern, Word, WordSet},
7};
8
9use super::{Expr, Optional, OwnedExprExt, 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    // Single word token methods
88
89    /// Construct a new sequence with a [`Word`] at the beginning of the operation list.
90    pub fn any_capitalization_of(word: &'static str) -> Self {
91        Self::default().then_any_capitalization_of(word)
92    }
93
94    /// Shorthand for [`Self::any_capitalization_of`].
95    pub fn aco(word: &'static str) -> Self {
96        Self::any_capitalization_of(word)
97    }
98
99    /// Match any word from the given set of words, case-insensitive.
100    pub fn word_set(words: &'static [&'static str]) -> Self {
101        Self::default().then_word_set(words)
102    }
103
104    /// Match any word.
105    pub fn any_word() -> Self {
106        Self::default().then_any_word()
107    }
108
109    // Expressions of more than one token
110
111    // Multiple expressions
112
113    /// Match the first of multiple expressions.
114    pub fn any_of(exprs: Vec<Box<dyn Expr>>) -> Self {
115        Self::default().then_any_of(exprs)
116    }
117
118    /// Will be accepted unless the condition matches.
119    pub fn unless(condition: impl Expr + 'static) -> Self {
120        Self::default().then_unless(condition)
121    }
122
123    // Builder methods
124
125    /// Push an [expression](Expr) to the operation list.
126    pub fn then(mut self, expr: impl Expr + 'static) -> Self {
127        self.exprs.push(Box::new(expr));
128        self
129    }
130
131    /// Pushes an expression that could move the cursor to the sequence, but does not require it.
132    pub fn then_optional(mut self, expr: impl Expr + 'static) -> Self {
133        self.exprs.push(Box::new(Optional::new(expr)));
134        self
135    }
136
137    /// Pushes an expression that will match any of the provided expressions.
138    ///
139    /// If more than one of the provided expressions match, this function provides no guarantee
140    /// as to which match will end up being used. If you need to get the longest of multiple
141    /// matches, use [`Self::then_longest_of()`] instead.
142    pub fn then_any_of(mut self, exprs: Vec<Box<dyn Expr>>) -> Self {
143        self.exprs.push(Box::new(FirstMatchOf::new(exprs)));
144        self
145    }
146
147    /// Pushes an expression that will match the longest of the provided expressions.
148    ///
149    /// If you don't need the longest match, prefer using the short-circuiting
150    /// [`Self::then_any_of()`] instead.
151    pub fn then_longest_of(mut self, exprs: Vec<Box<dyn Expr>>) -> Self {
152        self.exprs.push(Box::new(LongestMatchOf::new(exprs)));
153        self
154    }
155
156    /// Appends the steps in `other` onto the end of `self`.
157    /// This is more efficient than [`Self::then`] because it avoids pointer redirection.
158    pub fn then_seq(mut self, mut other: Self) -> Self {
159        self.exprs.append(&mut other.exprs);
160        self
161    }
162
163    /// Pushes an expression that will match any word from the given set of words, case-insensitive.
164    pub fn then_word_set(self, words: &'static [&'static str]) -> Self {
165        self.then(WordSet::new(words))
166    }
167
168    /// Matches any token whose `Kind` exactly matches.
169    pub fn then_strict(self, kind: TokenKind) -> Self {
170        self.then(move |tok: &Token, _source: &[char]| tok.kind == kind)
171    }
172
173    /// Match against one or more whitespace tokens.
174    pub fn then_whitespace(self) -> Self {
175        self.then(WhitespacePattern)
176    }
177
178    /// Match against one or more whitespace tokens.
179    pub fn then_whitespace_or_hyphen(self) -> Self {
180        self.then(WhitespacePattern.or(|tok: &Token, _: &[char]| tok.kind.is_hyphen()))
181    }
182
183    /// Shorthand for [`Self::then_whitespace_or_hyphen`].
184    pub fn t_ws_h(self) -> Self {
185        self.then_whitespace_or_hyphen()
186    }
187
188    /// Shorthand for [`Self::then_whitespace`].
189    pub fn t_ws(self) -> Self {
190        self.then_whitespace()
191    }
192
193    pub fn then_one_or_more(self, expr: impl Expr + 'static) -> Self {
194        self.then(Repeating::new(Box::new(expr), 1))
195    }
196
197    /// Create a new condition that will step one token forward if met.
198    /// If the condition is _not_ met, the whole expression returns `None`.
199    ///
200    /// This can be used to build out exceptions to other rules.
201    ///
202    /// See [`UnlessStep`] for more info.
203    pub fn then_unless(self, condition: impl Expr + 'static) -> Self {
204        self.then(UnlessStep::new(condition, |_tok: &Token, _src: &[char]| {
205            true
206        }))
207    }
208
209    /// Match any single token.
210    ///
211    /// See [`AnyPattern`] for more info.
212    pub fn then_anything(self) -> Self {
213        self.then(AnyPattern)
214    }
215
216    /// Match any single token.
217    ///
218    /// Shorthand for [`Self::then_anything`].
219    pub fn t_any(self) -> Self {
220        self.then_anything()
221    }
222
223    // Word matching methods
224
225    /// Matches any word.
226    pub fn then_any_word(self) -> Self {
227        self.then(|tok: &Token, _source: &[char]| tok.kind.is_word())
228    }
229
230    /// Match examples of `word` that have any capitalization.
231    pub fn then_any_capitalization_of(self, word: &'static str) -> Self {
232        self.then(Word::new(word))
233    }
234
235    /// Shorthand for [`Self::then_any_capitalization_of`].
236    pub fn t_aco(self, word: &'static str) -> Self {
237        self.then_any_capitalization_of(word)
238    }
239
240    /// Match examples of `word` case-sensitively.
241    pub fn then_exact_word(self, word: &'static str) -> Self {
242        self.then(Word::new_exact(word))
243    }
244
245    /// Match a fixed phrase.
246    pub fn then_fixed_phrase(self, phrase: &'static str) -> Self {
247        self.then(FixedPhrase::from_phrase(phrase))
248    }
249
250    /// Match any word except the ones in `words`.
251    pub fn then_word_except(self, words: &'static [&'static str]) -> Self {
252        self.then(move |tok: &Token, src: &[char]| {
253            !tok.kind.is_word()
254                || !words
255                    .iter()
256                    .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
257        })
258    }
259
260    // Token kind/predicate matching methods
261
262    // One kind
263
264    /// Match a token of a given kind which is not in the list of words.
265    pub fn then_kind_except<F>(self, pred_is: F, ex: &'static [&'static str]) -> Self
266    where
267        F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
268    {
269        self.then(move |tok: &Token, src: &[char]| {
270            pred_is(&tok.kind)
271                && !ex
272                    .iter()
273                    .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
274        })
275    }
276
277    // Two kinds
278
279    /// Match a token where both token kind predicates return true.
280    /// For instance, a word that can be both noun and verb.
281    pub fn then_kind_both<F1, F2>(self, pred_is_1: F1, pred_is_2: F2) -> Self
282    where
283        F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
284        F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
285    {
286        self.then(move |tok: &Token, _source: &[char]| pred_is_1(&tok.kind) && pred_is_2(&tok.kind))
287    }
288
289    /// Match a token where either of the two token kind predicates returns true.
290    /// For instance, an adjetive or an adverb.
291    pub fn then_kind_either<F1, F2>(self, pred_is_1: F1, pred_is_2: F2) -> Self
292    where
293        F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
294        F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
295    {
296        self.then(move |tok: &Token, _source: &[char]| pred_is_1(&tok.kind) || pred_is_2(&tok.kind))
297    }
298
299    /// Match a token where the first token kind predicate returns true and the second returns false.
300    /// For instance, a word that can be a noun but cannot be a verb.
301    pub fn then_kind_is_but_is_not<F1, F2>(self, pred_is: F1, pred_not: F2) -> Self
302    where
303        F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
304        F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
305    {
306        self.then(move |tok: &Token, _source: &[char]| pred_is(&tok.kind) && !pred_not(&tok.kind))
307    }
308
309    /// Match a token where the first token kind predicate returns true and the second returns false,
310    /// and the token is not in the list of exceptions.
311    pub fn then_kind_is_but_is_not_except<F1, F2>(
312        self,
313        pred_is: F1,
314        pred_not: F2,
315        ex: &'static [&'static str],
316    ) -> Self
317    where
318        F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
319        F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
320    {
321        self.then(move |tok: &Token, src: &[char]| {
322            pred_is(&tok.kind)
323                && !pred_not(&tok.kind)
324                && !ex
325                    .iter()
326                    .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
327        })
328    }
329
330    gen_then_from_is!(sentence_terminator);
331    // More than two kinds
332
333    /// Match a token where any of the token kind predicates returns true.
334    /// Like `then_kind_either` but for more than two predicates.
335    pub fn then_kind_any<F>(self, preds_is: &'static [F]) -> Self
336    where
337        F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
338    {
339        self.then(move |tok: &Token, _source: &[char]| preds_is.iter().any(|pred| pred(&tok.kind)))
340    }
341
342    /// Match a token where any of the token kind predicates returns true,
343    /// and the word is not in the list of exceptions.
344    pub fn then_kind_any_except<F>(
345        self,
346        preds_is: &'static [F],
347        ex: &'static [&'static str],
348    ) -> Self
349    where
350        F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
351    {
352        self.then(move |tok: &Token, src: &[char]| {
353            preds_is.iter().any(|pred| pred(&tok.kind))
354                && !ex
355                    .iter()
356                    .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
357        })
358    }
359
360    /// Match a token where any of the token kind predicates returns true,
361    /// or the token is in the list of words.
362    pub fn then_kind_any_or_words<F>(
363        self,
364        preds: &'static [F],
365        words: &'static [&'static str],
366    ) -> Self
367    where
368        F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
369    {
370        self.then(move |tok: &Token, src: &[char]| {
371            preds.iter().any(|pred| pred(&tok.kind))
372                // && !words
373                || words
374                    .iter()
375                    .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
376        })
377    }
378
379    /// Match a token where any of the first token kind predicates returns true,
380    /// the second returns false, and the token is not in the list of exceptions.    
381    pub fn then_kind_any_but_not_except<F1, F2>(
382        self,
383        preds_is: &'static [F1],
384        pred_not: F2,
385        ex: &'static [&'static str],
386    ) -> Self
387    where
388        F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
389        F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
390    {
391        self.then(move |tok: &Token, src: &[char]| {
392            preds_is.iter().any(|pred| pred(&tok.kind))
393                && !pred_not(&tok.kind)
394                && !ex
395                    .iter()
396                    .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
397        })
398    }
399
400    // Word property matching methods
401
402    // Out-of-vocabulary word. (Words not in the dictionary)
403    gen_then_from_is!(oov);
404    gen_then_from_is!(swear);
405
406    // Part-of-speech matching methods
407
408    // Nominals (nouns and pronouns)
409
410    gen_then_from_is!(nominal);
411    gen_then_from_is!(plural_nominal);
412    gen_then_from_is!(non_plural_nominal);
413    gen_then_from_is!(possessive_nominal);
414
415    // Nouns
416
417    gen_then_from_is!(noun);
418    gen_then_from_is!(proper_noun);
419    gen_then_from_is!(mass_noun_only);
420
421    // Pronouns
422
423    gen_then_from_is!(pronoun);
424    gen_then_from_is!(personal_pronoun);
425    gen_then_from_is!(first_person_singular_pronoun);
426    gen_then_from_is!(first_person_plural_pronoun);
427    gen_then_from_is!(second_person_pronoun);
428    gen_then_from_is!(third_person_pronoun);
429    gen_then_from_is!(third_person_singular_pronoun);
430    gen_then_from_is!(third_person_plural_pronoun);
431    gen_then_from_is!(subject_pronoun);
432    gen_then_from_is!(object_pronoun);
433
434    // Verbs
435
436    gen_then_from_is!(verb);
437    gen_then_from_is!(auxiliary_verb);
438    gen_then_from_is!(linking_verb);
439    gen_then_from_is!(verb_lemma);
440    gen_then_from_is!(verb_simple_past_form);
441    gen_then_from_is!(verb_past_participle_form);
442
443    // Adjectives
444
445    gen_then_from_is!(adjective);
446    gen_then_from_is!(positive_adjective);
447    gen_then_from_is!(comparative_adjective);
448    gen_then_from_is!(superlative_adjective);
449
450    // Adverbs
451
452    gen_then_from_is!(adverb);
453
454    // Determiners
455
456    gen_then_from_is!(determiner);
457    gen_then_from_is!(demonstrative_determiner);
458    gen_then_from_is!(quantifier);
459    gen_then_from_is!(non_quantifier_determiner);
460
461    /// Push an [`IndefiniteArticle`] to the end of the operation list.
462    pub fn then_indefinite_article(self) -> Self {
463        self.then(IndefiniteArticle::default())
464    }
465
466    // Other parts of speech
467
468    gen_then_from_is!(conjunction);
469    gen_then_from_is!(preposition);
470
471    // Punctuation
472
473    gen_then_from_is!(punctuation);
474    gen_then_from_is!(apostrophe);
475    gen_then_from_is!(comma);
476    gen_then_from_is!(hyphen);
477    gen_then_from_is!(period);
478    gen_then_from_is!(semicolon);
479    gen_then_from_is!(quote);
480
481    // Other
482
483    gen_then_from_is!(number);
484    gen_then_from_is!(case_separator);
485    gen_then_from_is!(likely_homograph);
486}
487
488impl<S> From<S> for SequenceExpr
489where
490    S: Step + 'static,
491{
492    fn from(step: S) -> Self {
493        Self {
494            exprs: vec![Box::new(step)],
495        }
496    }
497}
498
499#[cfg(test)]
500mod tests {
501    use crate::{
502        Document, TokenKind,
503        expr::{ExprExt, SequenceExpr},
504        linting::tests::SpanVecExt,
505    };
506
507    #[test]
508    fn test_kind_both() {
509        let noun_and_verb =
510            SequenceExpr::default().then_kind_both(TokenKind::is_noun, TokenKind::is_verb);
511        let doc = Document::new_plain_english_curated("Use a good example.");
512        let matches = noun_and_verb.iter_matches_in_doc(&doc).collect::<Vec<_>>();
513        assert_eq!(matches.to_strings(&doc), vec!["Use", "good", "example"]);
514    }
515
516    #[test]
517    fn test_adjective_or_determiner() {
518        let expr = SequenceExpr::default()
519            .then_kind_either(TokenKind::is_adjective, TokenKind::is_determiner);
520        let doc = Document::new_plain_english_curated("Use a good example.");
521        let matches = expr.iter_matches_in_doc(&doc).collect::<Vec<_>>();
522        assert_eq!(matches.to_strings(&doc), vec!["a", "good"]);
523    }
524
525    #[test]
526    fn test_noun_but_not_adjective() {
527        let expr = SequenceExpr::default()
528            .then_kind_is_but_is_not(TokenKind::is_noun, TokenKind::is_adjective);
529        let doc = Document::new_plain_english_curated("Use a good example.");
530        let matches = expr.iter_matches_in_doc(&doc).collect::<Vec<_>>();
531        assert_eq!(matches.to_strings(&doc), vec!["Use", "example"]);
532    }
533}