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
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 {
89 Self::default().then_any_capitalization_of(word)
90 }
91
92 pub fn aco(word: &'static str) -> Self {
94 Self::any_capitalization_of(word)
95 }
96
97 pub fn word_set(words: &'static [&'static str]) -> Self {
99 Self::default().then_word_set(words)
100 }
101
102 pub fn then(mut self, expr: impl Expr + 'static) -> Self {
106 self.exprs.push(Box::new(expr));
107 self
108 }
109
110 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 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 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 pub fn then_seq(mut self, mut other: Self) -> Self {
138 self.exprs.append(&mut other.exprs);
139 self
140 }
141
142 pub fn then_word_set(self, words: &'static [&'static str]) -> Self {
144 self.then(WordSet::new(words))
145 }
146
147 pub fn then_strict(self, kind: TokenKind) -> Self {
149 self.then(move |tok: &Token, _source: &[char]| tok.kind == kind)
150 }
151
152 pub fn then_whitespace(self) -> Self {
154 self.then(WhitespacePattern)
155 }
156
157 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 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 pub fn then_anything(self) -> Self {
182 self.then(AnyPattern)
183 }
184
185 pub fn t_any(self) -> Self {
189 self.then_anything()
190 }
191
192 pub fn then_any_word(self) -> Self {
196 self.then(|tok: &Token, _source: &[char]| tok.kind.is_word())
197 }
198
199 pub fn then_any_capitalization_of(self, word: &'static str) -> Self {
201 self.then(Word::new(word))
202 }
203
204 pub fn t_aco(self, word: &'static str) -> Self {
206 self.then_any_capitalization_of(word)
207 }
208
209 pub fn then_exact_word(self, word: &'static str) -> Self {
211 self.then(Word::new_exact(word))
212 }
213
214 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 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 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 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 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 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 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 gen_then_from_is!(oov);
295
296 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 gen_then_from_is!(noun);
308 gen_then_from_is!(proper_noun);
309 gen_then_from_is!(mass_noun_only);
310
311 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 gen_then_from_is!(verb);
325 gen_then_from_is!(auxiliary_verb);
326 gen_then_from_is!(linking_verb);
327
328 gen_then_from_is!(adjective);
331 gen_then_from_is!(positive_adjective);
332 gen_then_from_is!(comparative_adjective);
333
334 gen_then_from_is!(adverb);
337
338 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 pub fn then_indefinite_article(self) -> Self {
347 self.then(IndefiniteArticle::default())
348 }
349
350 gen_then_from_is!(conjunction);
353 gen_then_from_is!(preposition);
354
355 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 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}