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, 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(|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 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 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 if out.end > cursor {
73 cursor = out.end;
74 } else if out.start < cursor {
75 cursor = out.start;
76 }
77 }
79
80 Some(window)
81 }
82}
83
84impl SequenceExpr {
85 pub fn any_capitalization_of(word: &'static str) -> Self {
91 Self::default().then_any_capitalization_of(word)
92 }
93
94 pub fn aco(word: &'static str) -> Self {
96 Self::any_capitalization_of(word)
97 }
98
99 pub fn word_set(words: &'static [&'static str]) -> Self {
101 Self::default().then_word_set(words)
102 }
103
104 pub fn any_word() -> Self {
106 Self::default().then_any_word()
107 }
108
109 pub fn any_of(exprs: Vec<Box<dyn Expr>>) -> Self {
115 Self::default().then_any_of(exprs)
116 }
117
118 pub fn unless(condition: impl Expr + 'static) -> Self {
120 Self::default().then_unless(condition)
121 }
122
123 pub fn then(mut self, expr: impl Expr + 'static) -> Self {
127 self.exprs.push(Box::new(expr));
128 self
129 }
130
131 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 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 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 pub fn then_seq(mut self, mut other: Self) -> Self {
159 self.exprs.append(&mut other.exprs);
160 self
161 }
162
163 pub fn then_word_set(self, words: &'static [&'static str]) -> Self {
165 self.then(WordSet::new(words))
166 }
167
168 pub fn then_strict(self, kind: TokenKind) -> Self {
170 self.then(move |tok: &Token, _source: &[char]| tok.kind == kind)
171 }
172
173 pub fn then_whitespace(self) -> Self {
175 self.then(WhitespacePattern)
176 }
177
178 pub fn t_ws(self) -> Self {
180 self.then_whitespace()
181 }
182
183 pub fn then_one_or_more(self, expr: impl Expr + 'static) -> Self {
184 self.then(Repeating::new(Box::new(expr), 1))
185 }
186
187 pub fn then_unless(self, condition: impl Expr + 'static) -> Self {
194 self.then(UnlessStep::new(condition, |_tok: &Token, _src: &[char]| {
195 true
196 }))
197 }
198
199 pub fn then_anything(self) -> Self {
203 self.then(AnyPattern)
204 }
205
206 pub fn t_any(self) -> Self {
210 self.then_anything()
211 }
212
213 pub fn then_any_word(self) -> Self {
217 self.then(|tok: &Token, _source: &[char]| tok.kind.is_word())
218 }
219
220 pub fn then_any_capitalization_of(self, word: &'static str) -> Self {
222 self.then(Word::new(word))
223 }
224
225 pub fn t_aco(self, word: &'static str) -> Self {
227 self.then_any_capitalization_of(word)
228 }
229
230 pub fn then_exact_word(self, word: &'static str) -> Self {
232 self.then(Word::new_exact(word))
233 }
234
235 pub fn then_fixed_phrase(self, phrase: &'static str) -> Self {
237 self.then(FixedPhrase::from_phrase(phrase))
238 }
239
240 pub fn then_word_except(self, words: &'static [&'static str]) -> Self {
242 self.then(move |tok: &Token, src: &[char]| {
243 !tok.kind.is_word()
244 || !words
245 .iter()
246 .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
247 })
248 }
249
250 pub fn then_kind_except<F>(self, pred_is: F, ex: &'static [&'static str]) -> Self
256 where
257 F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
258 {
259 self.then(move |tok: &Token, src: &[char]| {
260 pred_is(&tok.kind)
261 && !ex
262 .iter()
263 .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
264 })
265 }
266
267 pub fn then_kind_both<F1, F2>(self, pred_is_1: F1, pred_is_2: F2) -> Self
272 where
273 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
274 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
275 {
276 self.then(move |tok: &Token, _source: &[char]| pred_is_1(&tok.kind) && pred_is_2(&tok.kind))
277 }
278
279 pub fn then_kind_either<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 pub fn then_kind_is_but_is_not<F1, F2>(self, pred_is: F1, pred_not: 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(&tok.kind) && !pred_not(&tok.kind))
297 }
298
299 pub fn then_kind_is_but_is_not_except<F1, F2>(
302 self,
303 pred_is: F1,
304 pred_not: F2,
305 ex: &'static [&'static str],
306 ) -> Self
307 where
308 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
309 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
310 {
311 self.then(move |tok: &Token, src: &[char]| {
312 pred_is(&tok.kind)
313 && !pred_not(&tok.kind)
314 && !ex
315 .iter()
316 .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
317 })
318 }
319
320 gen_then_from_is!(sentence_terminator);
321 pub fn then_kind_any<F>(self, preds_is: &'static [F]) -> Self
326 where
327 F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
328 {
329 self.then(move |tok: &Token, _source: &[char]| preds_is.iter().any(|pred| pred(&tok.kind)))
330 }
331
332 pub fn then_kind_any_except<F>(
335 self,
336 preds_is: &'static [F],
337 ex: &'static [&'static str],
338 ) -> Self
339 where
340 F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
341 {
342 self.then(move |tok: &Token, src: &[char]| {
343 preds_is.iter().any(|pred| pred(&tok.kind))
344 && !ex
345 .iter()
346 .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
347 })
348 }
349
350 pub fn then_kind_any_or_words<F>(
353 self,
354 preds: &'static [F],
355 words: &'static [&'static str],
356 ) -> Self
357 where
358 F: Fn(&TokenKind) -> bool + Send + Sync + 'static,
359 {
360 self.then(move |tok: &Token, src: &[char]| {
361 preds.iter().any(|pred| pred(&tok.kind))
362 || words
364 .iter()
365 .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
366 })
367 }
368
369 pub fn then_kind_any_but_not_except<F1, F2>(
372 self,
373 preds_is: &'static [F1],
374 pred_not: F2,
375 ex: &'static [&'static str],
376 ) -> Self
377 where
378 F1: Fn(&TokenKind) -> bool + Send + Sync + 'static,
379 F2: Fn(&TokenKind) -> bool + Send + Sync + 'static,
380 {
381 self.then(move |tok: &Token, src: &[char]| {
382 preds_is.iter().any(|pred| pred(&tok.kind))
383 && !pred_not(&tok.kind)
384 && !ex
385 .iter()
386 .any(|&word| tok.span.get_content(src).eq_ignore_ascii_case_str(word))
387 })
388 }
389
390 gen_then_from_is!(oov);
394 gen_then_from_is!(swear);
395
396 gen_then_from_is!(nominal);
401 gen_then_from_is!(plural_nominal);
402 gen_then_from_is!(non_plural_nominal);
403 gen_then_from_is!(possessive_nominal);
404
405 gen_then_from_is!(noun);
408 gen_then_from_is!(proper_noun);
409 gen_then_from_is!(mass_noun_only);
410
411 gen_then_from_is!(pronoun);
414 gen_then_from_is!(personal_pronoun);
415 gen_then_from_is!(first_person_singular_pronoun);
416 gen_then_from_is!(first_person_plural_pronoun);
417 gen_then_from_is!(second_person_pronoun);
418 gen_then_from_is!(third_person_pronoun);
419 gen_then_from_is!(third_person_singular_pronoun);
420 gen_then_from_is!(third_person_plural_pronoun);
421 gen_then_from_is!(subject_pronoun);
422 gen_then_from_is!(object_pronoun);
423
424 gen_then_from_is!(verb);
427 gen_then_from_is!(auxiliary_verb);
428 gen_then_from_is!(linking_verb);
429 gen_then_from_is!(verb_lemma);
430 gen_then_from_is!(verb_simple_past_form);
431 gen_then_from_is!(verb_past_participle_form);
432
433 gen_then_from_is!(adjective);
436 gen_then_from_is!(positive_adjective);
437 gen_then_from_is!(comparative_adjective);
438 gen_then_from_is!(superlative_adjective);
439
440 gen_then_from_is!(adverb);
443
444 gen_then_from_is!(determiner);
447 gen_then_from_is!(demonstrative_determiner);
448 gen_then_from_is!(quantifier);
449 gen_then_from_is!(non_quantifier_determiner);
450
451 pub fn then_indefinite_article(self) -> Self {
453 self.then(IndefiniteArticle::default())
454 }
455
456 gen_then_from_is!(conjunction);
459 gen_then_from_is!(preposition);
460
461 gen_then_from_is!(punctuation);
464 gen_then_from_is!(apostrophe);
465 gen_then_from_is!(comma);
466 gen_then_from_is!(hyphen);
467 gen_then_from_is!(period);
468 gen_then_from_is!(semicolon);
469 gen_then_from_is!(quote);
470
471 gen_then_from_is!(number);
474 gen_then_from_is!(case_separator);
475 gen_then_from_is!(likely_homograph);
476}
477
478impl<S> From<S> for SequenceExpr
479where
480 S: Step + 'static,
481{
482 fn from(step: S) -> Self {
483 Self {
484 exprs: vec![Box::new(step)],
485 }
486 }
487}
488
489#[cfg(test)]
490mod tests {
491 use crate::{
492 Document, TokenKind,
493 expr::{ExprExt, SequenceExpr},
494 linting::tests::SpanVecExt,
495 };
496
497 #[test]
498 fn test_kind_both() {
499 let noun_and_verb =
500 SequenceExpr::default().then_kind_both(TokenKind::is_noun, TokenKind::is_verb);
501 let doc = Document::new_plain_english_curated("Use a good example.");
502 let matches = noun_and_verb.iter_matches_in_doc(&doc).collect::<Vec<_>>();
503 assert_eq!(matches.to_strings(&doc), vec!["Use", "good", "example"]);
504 }
505
506 #[test]
507 fn test_adjective_or_determiner() {
508 let expr = SequenceExpr::default()
509 .then_kind_either(TokenKind::is_adjective, TokenKind::is_determiner);
510 let doc = Document::new_plain_english_curated("Use a good example.");
511 let matches = expr.iter_matches_in_doc(&doc).collect::<Vec<_>>();
512 assert_eq!(matches.to_strings(&doc), vec!["a", "good"]);
513 }
514
515 #[test]
516 fn test_noun_but_not_adjective() {
517 let expr = SequenceExpr::default()
518 .then_kind_is_but_is_not(TokenKind::is_noun, TokenKind::is_adjective);
519 let doc = Document::new_plain_english_curated("Use a good example.");
520 let matches = expr.iter_matches_in_doc(&doc).collect::<Vec<_>>();
521 assert_eq!(matches.to_strings(&doc), vec!["Use", "example"]);
522 }
523}