harper_core/patterns/
derived_from.rs

1use crate::spell::WordId;
2
3use super::Pattern;
4
5/// A [Pattern] that looks for Word tokens that are either derived from a given word, or the word
6/// itself.
7///
8/// For example, this will match "call" as well as "recall", "calling", etc.
9pub struct DerivedFrom {
10    word_id: WordId,
11}
12
13impl DerivedFrom {
14    pub fn new_from_str(word: &str) -> DerivedFrom {
15        Self::new(WordId::from_word_str(word))
16    }
17
18    pub fn new_from_chars(word: &[char]) -> DerivedFrom {
19        Self::new(WordId::from_word_chars(word))
20    }
21
22    pub fn new(word_id: WordId) -> Self {
23        Self { word_id }
24    }
25}
26
27impl Pattern for DerivedFrom {
28    fn matches(&self, tokens: &[crate::Token], source: &[char]) -> Option<usize> {
29        let tok = tokens.first()?;
30        let metadata = tok.kind.as_word()?.as_ref()?;
31
32        if metadata.derived_from == Some(self.word_id) {
33            return Some(1);
34        }
35
36        let chars = tok.span.get_content(source);
37        let word_id = WordId::from_word_chars(chars);
38
39        if word_id == self.word_id {
40            return Some(1);
41        }
42
43        None
44    }
45}