harper_core/expr/
sequence_expr.rs

1use paste::paste;
2
3use crate::{
4    Span, Token, TokenKind,
5    patterns::{AnyPattern, IndefiniteArticle, WhitespacePattern, Word},
6};
7
8use super::{Expr, Optional, Repeating, Step, UnlessStep};
9
10#[derive(Default)]
11pub struct SequenceExpr {
12    exprs: Vec<Box<dyn Expr>>,
13}
14
15/// Generate a `then_*` method from an available `is_*` function on [`TokenKind`].
16macro_rules! gen_then_from_is {
17    ($quality:ident) => {
18        paste! {
19            pub fn [< then_$quality >] (self) -> Self{
20                self.then(|tok: &Token, _source: &[char]| {
21                    tok.kind.[< is_$quality >]()
22                })
23            }
24
25            pub fn [< then_one_or_more_$quality s >] (self) -> Self{
26                self.then_one_or_more(Box::new(|tok: &Token, _source: &[char]| {
27                    tok.kind.[< is_$quality >]()
28                }))
29            }
30
31            pub fn [< then_anything_but_$quality >] (self) -> Self{
32                self.then(|tok: &Token, _source: &[char]| {
33                    if tok.kind.[< is_$quality >](){
34                        false
35                    }else{
36                        true
37                    }
38                })
39            }
40        }
41    };
42}
43
44impl Expr for SequenceExpr {
45    /// Run the expression starting at an index, returning the total matched window.
46    ///
47    /// If any step returns `None`, the entire expression does as well.
48    fn run(&self, mut cursor: usize, tokens: &[Token], source: &[char]) -> Option<Span> {
49        let mut window = Span::new_with_len(cursor, 0);
50
51        for cur_expr in &self.exprs {
52            let out = cur_expr.run(cursor, tokens, source)?;
53
54            window.expand_to_include(out.start);
55            window.expand_to_include(out.end.checked_sub(1).unwrap_or(out.start));
56
57            if out.start < cursor {
58                cursor = out.start;
59            } else {
60                cursor = out.end;
61            }
62        }
63
64        Some(window)
65    }
66}
67
68impl SequenceExpr {
69    pub fn then(mut self, expr: impl Expr + 'static) -> Self {
70        self.exprs.push(Box::new(expr));
71        self
72    }
73
74    /// Pushes an expression that could move the cursor to the sequence, but does not require it.
75    pub fn then_optional(mut self, expr: impl Expr + 'static) -> Self {
76        self.exprs.push(Box::new(Optional::new(expr)));
77        self
78    }
79
80    /// Appends the steps in `other` onto the end of `self`.
81    pub fn then_expr(mut self, mut other: Self) -> Self {
82        self.exprs.append(&mut other.exprs);
83        self
84    }
85
86    pub fn then_indefinite_article(self) -> Self {
87        self.then(IndefiniteArticle::default())
88    }
89
90    /// Match examples of `word` case-sensitively.
91    pub fn then_exact_word(self, word: &'static str) -> Self {
92        self.then(Word::new_exact(word))
93    }
94
95    /// Shorthand for [`Self::any_capitalization_of`].
96    pub fn aco(word: &'static str) -> Self {
97        Self::any_capitalization_of(word)
98    }
99
100    pub fn any_capitalization_of(word: &'static str) -> Self {
101        Self::default().then_any_capitalization_of(word)
102    }
103
104    /// Shorthand for [`Self::then_any_capitalization_of`].
105    pub fn t_aco(self, word: &'static str) -> Self {
106        self.then_any_capitalization_of(word)
107    }
108
109    /// Match examples of `word` that have any capitalization.
110    pub fn then_any_capitalization_of(self, word: &'static str) -> Self {
111        self.then(Word::new(word))
112    }
113
114    /// Matches any word.
115    pub fn then_any_word(self) -> Self {
116        self.then(|tok: &Token, _source: &[char]| tok.kind.is_word())
117    }
118
119    /// Matches any token whose `Kind` exactly matches.
120    pub fn then_strict(self, kind: TokenKind) -> Self {
121        self.then(move |tok: &Token, _source: &[char]| tok.kind == kind)
122    }
123
124    /// Shorthand for [`Self::then_whitespace`].
125    pub fn t_ws(self) -> Self {
126        self.then_whitespace()
127    }
128
129    /// Match against one or more whitespace tokens.
130    pub fn then_whitespace(self) -> Self {
131        self.then(WhitespacePattern)
132    }
133
134    pub fn then_one_or_more(self, expr: impl Expr + 'static) -> Self {
135        self.then(Repeating::new(Box::new(expr), 1))
136    }
137
138    /// Create a new condition that will step one token forward if met.
139    pub fn if_not_then_step_one(self, condition: impl Expr + 'static) -> Self {
140        self.then(UnlessStep::new(condition, |_tok: &Token, _src: &[char]| {
141            true
142        }))
143    }
144
145    pub fn t_any(self) -> Self {
146        self.then_anything()
147    }
148
149    pub fn then_anything(self) -> Self {
150        self.then(AnyPattern)
151    }
152
153    gen_then_from_is!(nominal);
154    gen_then_from_is!(noun);
155    gen_then_from_is!(possessive_nominal);
156    gen_then_from_is!(plural_nominal);
157    gen_then_from_is!(verb);
158    gen_then_from_is!(auxiliary_verb);
159    gen_then_from_is!(linking_verb);
160    gen_then_from_is!(pronoun);
161    gen_then_from_is!(punctuation);
162    gen_then_from_is!(conjunction);
163    gen_then_from_is!(comma);
164    gen_then_from_is!(period);
165    gen_then_from_is!(number);
166    gen_then_from_is!(case_separator);
167    gen_then_from_is!(adverb);
168    gen_then_from_is!(adjective);
169    gen_then_from_is!(apostrophe);
170    gen_then_from_is!(hyphen);
171    gen_then_from_is!(determiner);
172    gen_then_from_is!(proper_noun);
173    gen_then_from_is!(preposition);
174    gen_then_from_is!(third_person_pronoun);
175    gen_then_from_is!(third_person_singular_pronoun);
176    gen_then_from_is!(third_person_plural_pronoun);
177    gen_then_from_is!(first_person_singular_pronoun);
178    gen_then_from_is!(first_person_plural_pronoun);
179    gen_then_from_is!(second_person_pronoun);
180    gen_then_from_is!(non_plural_nominal);
181}
182
183impl<S> From<S> for SequenceExpr
184where
185    S: Step + 'static,
186{
187    fn from(step: S) -> Self {
188        Self {
189            exprs: vec![Box::new(step)],
190        }
191    }
192}