1use paste::paste;
2
3use crate::{
4 CharStringExt, Lrc, 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
16macro_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_kind_where(|kind| {
23 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_kind_where(|kind| {
44 !kind.[< is_$quality >]()
45 })
46 }
47 }
48 };
49}
50
51impl Expr for SequenceExpr {
52 fn run(&self, mut cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span<Token>> {
56 let mut window = Span::empty(cursor);
57
58 for cur_expr in &self.exprs {
59 let out = cur_expr.run(cursor, tokens, source)?;
60
61 if out.end > out.start {
63 window.expand_to_include(out.start);
64 window.expand_to_include(out.end.checked_sub(1).unwrap_or(out.start));
65 }
66
67 if out.end > cursor {
69 cursor = out.end;
70 } else if out.start < cursor {
71 cursor = out.start;
72 }
73 }
75
76 Some(window)
77 }
78}
79
80impl SequenceExpr {
81 pub fn with(expr: impl Expr + 'static) -> Self {
85 Self::default().then(expr)
86 }
87
88 pub fn anything() -> Self {
92 Self::default().then_anything()
93 }
94
95 pub fn any_capitalization_of(word: &'static str) -> Self {
99 Self::default().then_any_capitalization_of(word)
100 }
101
102 pub fn aco(word: &'static str) -> Self {
104 Self::any_capitalization_of(word)
105 }
106
107 pub fn word_set(words: &'static [&'static str]) -> Self {
109 Self::default().then_word_set(words)
110 }
111
112 pub fn any_word() -> Self {
114 Self::default().then_any_word()
115 }
116
117 pub fn optional(expr: impl Expr + 'static) -> Self {
121 Self::default().then_optional(expr)
122 }
123
124 pub fn fixed_phrase(phrase: &'static str) -> Self {
126 Self::default().then_fixed_phrase(phrase)
127 }
128
129 pub fn any_of(exprs: Vec<Box<dyn Expr>>) -> Self {
133 Self::default().then_any_of(exprs)
134 }
135
136 pub fn longest_of(exprs: Vec<Box<dyn Expr>>) -> Self {
138 Self::default().then_longest_of(exprs)
139 }
140
141 pub fn whitespace() -> Self {
142 Self::default().then_whitespace()
143 }
144
145 pub fn unless(condition: impl Expr + 'static) -> Self {
147 Self::default().then_unless(condition)
148 }
149
150 pub fn then(mut self, expr: impl Expr + 'static) -> Self {
154 self.exprs.push(Box::new(expr));
155 self
156 }
157
158 pub fn then_boxed(mut self, expr: Box<dyn Expr>) -> Self {
160 self.exprs.push(expr);
161 self
162 }
163
164 pub fn then_optional(mut self, expr: impl Expr + 'static) -> Self {
166 self.exprs.push(Box::new(Optional::new(expr)));
167 self
168 }
169
170 pub fn then_any_of(mut self, exprs: Vec<Box<dyn Expr>>) -> Self {
176 self.exprs.push(Box::new(FirstMatchOf::new(exprs)));
177 self
178 }
179
180 pub fn then_longest_of(mut self, exprs: Vec<Box<dyn Expr>>) -> Self {
185 self.exprs.push(Box::new(LongestMatchOf::new(exprs)));
186 self
187 }
188
189 pub fn then_seq(mut self, mut other: Self) -> Self {
192 self.exprs.append(&mut other.exprs);
193 self
194 }
195
196 pub fn then_word_set(self, words: &'static [&'static str]) -> Self {
198 self.then(WordSet::new(words))
199 }
200
201 pub fn t_set(self, words: &'static [&'static str]) -> Self {
203 self.then_word_set(words)
204 }
205
206 pub fn then_whitespace(self) -> Self {
208 self.then(WhitespacePattern)
209 }
210
211 pub fn t_ws(self) -> Self {
213 self.then_whitespace()
214 }
215
216 pub fn then_whitespace_or_hyphen(self) -> Self {
218 self.then(WhitespacePattern.or(|tok: &Token, _: &[char]| tok.kind.is_hyphen()))
219 }
220
221 pub fn t_ws_h(self) -> Self {
223 self.then_whitespace_or_hyphen()
224 }
225
226 pub fn then_zero_or_more(self, expr: impl Expr + 'static) -> Self {
228 self.then(Repeating::new(Box::new(expr), 0))
229 }
230
231 pub fn then_one_or_more(self, expr: impl Expr + 'static) -> Self {
233 self.then(Repeating::new(Box::new(expr), 1))
234 }
235
236 pub fn then_zero_or_more_spaced(self, expr: impl Expr + 'static) -> Self {
238 let expr = Lrc::new(expr);
239 self.then(SequenceExpr::with(expr.clone()).then(Repeating::new(
240 Box::new(SequenceExpr::default().t_ws().then(expr)),
241 0,
242 )))
243 }
244
245 pub fn then_unless(self, condition: impl Expr + 'static) -> Self {
252 self.then(UnlessStep::new(condition, |_tok: &Token, _src: &[char]| {
253 true
254 }))
255 }
256
257 pub fn then_anything(self) -> Self {
261 self.then(AnyPattern)
262 }
263
264 pub fn t_any(self) -> Self {
268 self.then_anything()
269 }
270
271 pub fn then_any_word(self) -> Self {
275 self.then_kind_where(|kind| kind.is_word())
276 }
277
278 pub fn then_any_capitalization_of(self, word: &'static str) -> Self {
280 self.then(Word::new(word))
281 }
282
283 pub fn t_aco(self, word: &'static str) -> Self {
285 self.then_any_capitalization_of(word)
286 }
287
288 pub fn then_exact_word(self, word: &'static str) -> Self {
290 self.then(Word::new_exact(word))
291 }
292
293 pub fn then_fixed_phrase(self, phrase: &'static str) -> Self {
295 self.then(FixedPhrase::from_phrase(phrase))
296 }
297
298 pub fn then_word_except(self, words: &'static [&'static str]) -> Self {
300 self.then(move |tok: &Token, src: &[char]| {
301 !tok.kind.is_word() || !words.iter().any(|&word| tok.get_ch(src).eq_str(word))
302 })
303 }
304
305 pub fn then_kind(self, kind: TokenKind) -> Self {
311 self.then_kind_where(move |k| kind == *k)
312 }
313
314 pub fn then_kind_where<F>(mut self, predicate: F) -> Self
316 where
317 F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
318 {
319 self.exprs
320 .push(Box::new(move |tok: &Token, _source: &[char]| {
321 predicate(&tok.kind)
322 }));
323 self
324 }
325
326 pub fn then_kind_except<F>(self, pred_is: F, ex: &'static [&'static str]) -> Self
328 where
329 F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
330 {
331 self.then(move |tok: &Token, src: &[char]| {
332 pred_is(&tok.kind) && !ex.iter().any(|&word| tok.get_ch(src).eq_str(word))
333 })
334 }
335
336 pub fn then_kind_both<F1, F2>(self, pred_is_1: F1, pred_is_2: F2) -> Self
341 where
342 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
343 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
344 {
345 self.then_kind_where(move |k| pred_is_1(k) && pred_is_2(k))
346 }
347
348 pub fn then_kind_either<F1, F2>(self, pred_is_1: F1, pred_is_2: F2) -> Self
351 where
352 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
353 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
354 {
355 self.then_kind_where(move |k| pred_is_1(k) || pred_is_2(k))
356 }
357
358 pub fn then_kind_neither<F1, F2>(self, pred_isnt_1: F1, pred_isnt_2: F2) -> Self
361 where
362 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
363 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
364 {
365 self.then_kind_where(move |k| !pred_isnt_1(k) && !pred_isnt_2(k))
366 }
367
368 pub fn then_kind_is_but_is_not<F1, F2>(self, pred_is: F1, pred_not: F2) -> Self
371 where
372 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
373 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
374 {
375 self.then_kind_where(move |k| pred_is(k) && !pred_not(k))
376 }
377
378 pub fn then_kind_is_but_is_not_except<F1, F2>(
381 self,
382 pred_is: F1,
383 pred_not: F2,
384 ex: &'static [&'static str],
385 ) -> Self
386 where
387 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
388 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
389 {
390 self.then(move |tok: &Token, src: &[char]| {
391 pred_is(&tok.kind)
392 && !pred_not(&tok.kind)
393 && !ex.iter().any(|&word| tok.get_ch(src).eq_str(word))
394 })
395 }
396
397 pub fn then_kind_is_but_isnt_any_of<F1, F2>(
400 self,
401 pred_is: F1,
402 preds_isnt: &'static [F2],
403 ) -> Self
404 where
405 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
406 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
407 {
408 self.then_kind_where(move |k| pred_is(k) && !preds_isnt.iter().any(|pred| pred(k)))
409 }
410
411 pub fn then_kind_is_but_isnt_any_of_except<F1, F2>(
415 self,
416 pred_is: F1,
417 preds_isnt: &'static [F2],
418 ex: &'static [&'static str],
419 ) -> Self
420 where
421 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
422 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
423 {
424 self.then(move |tok: &Token, src: &[char]| {
425 pred_is(&tok.kind)
426 && !preds_isnt.iter().any(|pred| pred(&tok.kind))
427 && !ex.iter().any(|&word| tok.get_ch(src).eq_str(word))
428 })
429 }
430
431 pub fn then_kind_both_but_not<F1, F2, F3>(
437 self,
438 (pred_is_1, pred_is_2): (F1, F2),
439 pred_not: F3,
440 ) -> Self
441 where
442 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
443 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
444 F3: Fn(&TokenKind) -> bool + Send + Sync + 'static,
445 {
446 self.then_kind_where(move |k| pred_is_1(k) && pred_is_2(k) && !pred_not(k))
447 }
448
449 pub fn then_kind_any<F>(self, preds_is: &'static [F]) -> Self
452 where
453 F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
454 {
455 self.then_kind_where(move |k| preds_is.iter().any(|pred| pred(k)))
456 }
457
458 pub fn then_kind_none_of<F>(self, preds_isnt: &'static [F]) -> Self
461 where
462 F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
463 {
464 self.then_kind_where(move |k| preds_isnt.iter().all(|pred| !pred(k)))
465 }
466
467 pub fn then_kind_any_except<F>(
470 self,
471 preds_is: &'static [F],
472 ex: &'static [&'static str],
473 ) -> Self
474 where
475 F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
476 {
477 self.then(move |tok: &Token, src: &[char]| {
478 preds_is.iter().any(|pred| pred(&tok.kind))
479 && !ex.iter().any(|&word| tok.get_ch(src).eq_str(word))
480 })
481 }
482
483 pub fn then_kind_any_or_words<F>(
486 self,
487 preds: &'static [F],
488 words: &'static [&'static str],
489 ) -> Self
490 where
491 F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
492 {
493 self.then(move |tok: &Token, src: &[char]| {
494 preds.iter().any(|pred| pred(&tok.kind))
495 || words.iter().any(|&word| tok.get_ch(src).eq_str(word))
496 })
497 }
498
499 pub fn then_kind_any_but_not_except<F1, F2>(
502 self,
503 preds_is: &'static [F1],
504 pred_not: F2,
505 ex: &'static [&'static str],
506 ) -> Self
507 where
508 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
509 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
510 {
511 self.then(move |tok: &Token, src: &[char]| {
512 preds_is.iter().any(|pred| pred(&tok.kind))
513 && !pred_not(&tok.kind)
514 && !ex.iter().any(|&word| tok.get_ch(src).eq_str(word))
515 })
516 }
517
518 gen_then_from_is!(oov);
522 gen_then_from_is!(swear);
523
524 gen_then_from_is!(nominal);
529 gen_then_from_is!(plural_nominal);
530 gen_then_from_is!(non_plural_nominal);
531 gen_then_from_is!(possessive_nominal);
532
533 gen_then_from_is!(noun);
536 gen_then_from_is!(proper_noun);
537 gen_then_from_is!(plural_noun);
538 gen_then_from_is!(singular_noun);
539 gen_then_from_is!(mass_noun_only);
540
541 gen_then_from_is!(pronoun);
544 gen_then_from_is!(personal_pronoun);
545 gen_then_from_is!(first_person_singular_pronoun);
546 gen_then_from_is!(first_person_plural_pronoun);
547 gen_then_from_is!(second_person_pronoun);
548 gen_then_from_is!(third_person_pronoun);
549 gen_then_from_is!(third_person_singular_pronoun);
550 gen_then_from_is!(third_person_plural_pronoun);
551 gen_then_from_is!(subject_pronoun);
552 gen_then_from_is!(object_pronoun);
553
554 gen_then_from_is!(verb);
557 gen_then_from_is!(auxiliary_verb);
558 gen_then_from_is!(linking_verb);
559 gen_then_from_is!(verb_lemma);
560 gen_then_from_is!(verb_simple_past_form);
561 gen_then_from_is!(verb_past_participle_form);
562 gen_then_from_is!(verb_progressive_form);
563 gen_then_from_is!(verb_third_person_singular_present_form);
564
565 gen_then_from_is!(adjective);
568 gen_then_from_is!(positive_adjective);
569 gen_then_from_is!(comparative_adjective);
570 gen_then_from_is!(superlative_adjective);
571
572 gen_then_from_is!(adverb);
575 gen_then_from_is!(frequency_adverb);
576 gen_then_from_is!(degree_adverb);
577
578 gen_then_from_is!(determiner);
581 gen_then_from_is!(demonstrative_determiner);
582 gen_then_from_is!(possessive_determiner);
583 gen_then_from_is!(quantifier);
584 gen_then_from_is!(non_quantifier_determiner);
585 gen_then_from_is!(non_demonstrative_determiner);
586
587 pub fn then_indefinite_article(self) -> Self {
589 self.then(IndefiniteArticle::default())
590 }
591
592 gen_then_from_is!(conjunction);
595 gen_then_from_is!(preposition);
596
597 gen_then_from_is!(number);
600 gen_then_from_is!(cardinal_number);
601 gen_then_from_is!(ordinal_number);
602
603 gen_then_from_is!(punctuation);
606 gen_then_from_is!(apostrophe);
607 gen_then_from_is!(comma);
608 gen_then_from_is!(hyphen);
609 gen_then_from_is!(period);
610 gen_then_from_is!(semicolon);
611 gen_then_from_is!(acute);
612 gen_then_from_is!(quote);
613 gen_then_from_is!(backslash);
614 gen_then_from_is!(slash);
615 gen_then_from_is!(percent);
616
617 gen_then_from_is!(case_separator);
620 gen_then_from_is!(likely_homograph);
621 gen_then_from_is!(sentence_terminator);
622}
623
624impl<S> From<S> for SequenceExpr
625where
626 S: Step + 'static,
627{
628 fn from(step: S) -> Self {
629 Self {
630 exprs: vec![Box::new(step)],
631 }
632 }
633}
634
635#[cfg(test)]
636mod tests {
637 use crate::{
638 Document, TokenKind,
639 expr::{ExprExt, SequenceExpr},
640 linting::tests::SpanVecExt,
641 };
642
643 #[test]
644 fn test_kind_both() {
645 let noun_and_verb =
646 SequenceExpr::default().then_kind_both(TokenKind::is_noun, TokenKind::is_verb);
647 let doc = Document::new_plain_english_curated("Use a good example.");
648 let matches = noun_and_verb.iter_matches_in_doc(&doc).collect::<Vec<_>>();
649 assert_eq!(matches.to_strings(&doc), vec!["Use", "good", "example"]);
650 }
651
652 #[test]
653 fn test_adjective_or_determiner() {
654 let expr = SequenceExpr::default()
655 .then_kind_either(TokenKind::is_adjective, TokenKind::is_determiner);
656 let doc = Document::new_plain_english_curated("Use a good example.");
657 let matches = expr.iter_matches_in_doc(&doc).collect::<Vec<_>>();
658 assert_eq!(matches.to_strings(&doc), vec!["a", "good"]);
659 }
660
661 #[test]
662 fn test_noun_but_not_adjective() {
663 let expr = SequenceExpr::default()
664 .then_kind_is_but_is_not(TokenKind::is_noun, TokenKind::is_adjective);
665 let doc = Document::new_plain_english_curated("Use a good example.");
666 let matches = expr.iter_matches_in_doc(&doc).collect::<Vec<_>>();
667 assert_eq!(matches.to_strings(&doc), vec!["Use", "example"]);
668 }
669}