harper_core/
token_kind.rs

1use harper_brill::UPOS;
2use is_macro::Is;
3use serde::{Deserialize, Serialize};
4
5use crate::{Number, Punctuation, Quote, TokenKind::Word, WordMetadata};
6
7/// Generate wrapper code to pass a function call to the inner [`WordMetadata`],  
8/// if the token is indeed a word, while also emitting method-level documentation.
9macro_rules! delegate_to_metadata {
10    ($($method:ident),* $(,)?) => {
11        $(
12            #[doc = concat!(
13                "Delegates to [`WordMetadata::",
14                stringify!($method),
15                "`] when this token is a word.\n\n",
16                "Returns `false` if the token is not a word."
17            )]
18            pub fn $method(&self) -> bool {
19                let Word(Some(metadata)) = self else {
20                    return false;
21                };
22                metadata.$method()
23            }
24        )*
25    };
26}
27
28/// The parsed value of a [`Token`](crate::Token).
29/// Has a variety of queries available.
30/// If there is a query missing, it may be easy to implement by just calling the
31/// `delegate_to_metadata` macro.
32#[derive(Debug, Is, Clone, Serialize, Deserialize, Default, PartialOrd, Hash, Eq, PartialEq)]
33#[serde(tag = "kind", content = "value")]
34pub enum TokenKind {
35    /// `None` if the word does not exist in the dictionary.
36    Word(Option<WordMetadata>),
37    Punctuation(Punctuation),
38    Decade,
39    Number(Number),
40    /// A sequence of " " spaces.
41    Space(usize),
42    /// A sequence of "\n" newlines
43    Newline(usize),
44    EmailAddress,
45    Url,
46    Hostname,
47    /// A special token used for things like inline code blocks that should be
48    /// ignored by all linters.
49    #[default]
50    Unlintable,
51    ParagraphBreak,
52    Regexish,
53}
54
55impl TokenKind {
56    // Word metadata delegation methods grouped by part of speech
57    delegate_to_metadata! {
58        // Nominal methods (nouns and pronouns)
59        is_nominal,
60        is_noun,
61        is_pronoun,
62        is_proper_noun,
63        is_singular_nominal,
64        is_plural_nominal,
65        is_possessive_nominal,
66        is_non_plural_nominal,
67        is_singular_noun,
68        is_plural_noun,
69        is_non_plural_noun,
70        is_countable_noun,
71        is_non_countable_noun,
72        is_mass_noun,
73        is_mass_noun_only,
74        is_non_mass_noun,
75        is_singular_pronoun,
76        is_plural_pronoun,
77        is_non_plural_pronoun,
78        is_reflexive_pronoun,
79        is_personal_pronoun,
80        is_first_person_singular_pronoun,
81        is_first_person_plural_pronoun,
82        is_second_person_pronoun,
83        is_third_person_pronoun,
84        is_third_person_singular_pronoun,
85        is_third_person_plural_pronoun,
86        is_object_pronoun,
87        is_possessive_noun,
88        is_possessive_pronoun,
89
90        // Verb methods
91        is_verb,
92        is_auxiliary_verb,
93        is_linking_verb,
94        is_verb_lemma,
95        is_verb_past_form,
96        is_verb_progressive_form,
97        is_verb_third_person_singular_present_form,
98
99        // Adjective methods
100        is_adjective,
101        is_comparative_adjective,
102        is_superlative_adjective,
103        is_positive_adjective,
104
105        // Adverb methods
106        is_adverb,
107
108        // Determiner methods
109        is_determiner,
110        is_demonstrative_determiner,
111        is_possessive_determiner,
112        is_quantifier,
113        is_non_quantifier_determiner,
114
115        // Conjunction methods
116        is_conjunction,
117
118        // Generic word methods
119        is_swear,
120        is_likely_homograph,
121
122        // Orthography methods
123        is_lowercase,
124        is_titlecase,
125        is_allcaps,
126        is_lower_camel,
127        is_upper_camel
128    }
129
130    // Word metadata delegation methods not generated by macro
131    pub fn is_preposition(&self) -> bool {
132        let Word(Some(metadata)) = self else {
133            return false;
134        };
135        metadata.preposition
136    }
137
138    pub fn is_common_word(&self) -> bool {
139        let Word(Some(metadata)) = self else {
140            return true;
141        };
142        metadata.common
143    }
144
145    /// Checks whether a word token is out-of-vocabulary (not found in the dictionary).
146    ///
147    /// Returns `true` if the token is a word that was not found in the dictionary,
148    /// `false` if the token is a word found in the dictionary or is not a word token.
149    pub fn is_oov(&self) -> bool {
150        matches!(self, TokenKind::Word(None))
151    }
152
153    // Punctuation and symbol is-methods
154
155    pub fn is_open_square(&self) -> bool {
156        matches!(self, TokenKind::Punctuation(Punctuation::OpenSquare))
157    }
158
159    pub fn is_close_square(&self) -> bool {
160        matches!(self, TokenKind::Punctuation(Punctuation::CloseSquare))
161    }
162
163    pub fn is_open_round(&self) -> bool {
164        matches!(self, TokenKind::Punctuation(Punctuation::OpenRound))
165    }
166
167    pub fn is_close_round(&self) -> bool {
168        matches!(self, TokenKind::Punctuation(Punctuation::CloseRound))
169    }
170
171    pub fn is_pipe(&self) -> bool {
172        matches!(self, TokenKind::Punctuation(Punctuation::Pipe))
173    }
174
175    pub fn is_currency(&self) -> bool {
176        matches!(self, TokenKind::Punctuation(Punctuation::Currency(..)))
177    }
178
179    pub fn is_ellipsis(&self) -> bool {
180        matches!(self, TokenKind::Punctuation(Punctuation::Ellipsis))
181    }
182
183    pub fn is_hyphen(&self) -> bool {
184        matches!(self, TokenKind::Punctuation(Punctuation::Hyphen))
185    }
186
187    pub fn is_quote(&self) -> bool {
188        matches!(self, TokenKind::Punctuation(Punctuation::Quote(_)))
189    }
190
191    pub fn is_apostrophe(&self) -> bool {
192        matches!(self, TokenKind::Punctuation(Punctuation::Apostrophe))
193    }
194
195    pub fn is_period(&self) -> bool {
196        matches!(self, TokenKind::Punctuation(Punctuation::Period))
197    }
198
199    pub fn is_at(&self) -> bool {
200        matches!(self, TokenKind::Punctuation(Punctuation::At))
201    }
202
203    pub fn is_comma(&self) -> bool {
204        matches!(self, TokenKind::Punctuation(Punctuation::Comma))
205    }
206
207    pub fn is_semicolon(&self) -> bool {
208        matches!(self, TokenKind::Punctuation(Punctuation::Semicolon))
209    }
210
211    pub fn is_ampersand(&self) -> bool {
212        matches!(self, TokenKind::Punctuation(Punctuation::Ampersand))
213    }
214
215    // Miscellaneous is-methods
216
217    /// Checks whether a token is word-like--meaning it is more complex than punctuation and can
218    /// hold semantic meaning in the way a word does.
219    pub fn is_word_like(&self) -> bool {
220        matches!(
221            self,
222            TokenKind::Word(..)
223                | TokenKind::EmailAddress
224                | TokenKind::Hostname
225                | TokenKind::Decade
226                | TokenKind::Number(..)
227        )
228    }
229
230    pub(crate) fn is_chunk_terminator(&self) -> bool {
231        if self.is_sentence_terminator() {
232            return true;
233        }
234
235        match self {
236            TokenKind::Punctuation(punct) => {
237                matches!(
238                    punct,
239                    Punctuation::Comma | Punctuation::Quote { .. } | Punctuation::Colon
240                )
241            }
242            _ => false,
243        }
244    }
245
246    pub(crate) fn is_sentence_terminator(&self) -> bool {
247        match self {
248            TokenKind::Punctuation(punct) => [
249                Punctuation::Period,
250                Punctuation::Bang,
251                Punctuation::Question,
252            ]
253            .contains(punct),
254            TokenKind::ParagraphBreak => true,
255            _ => false,
256        }
257    }
258
259    /// Used by `crate::parsers::CollapseIdentifiers`
260    /// TODO: Separate this into two functions and add OR functionality to
261    /// pattern matching
262    pub fn is_case_separator(&self) -> bool {
263        matches!(self, TokenKind::Punctuation(Punctuation::Underscore))
264            || matches!(self, TokenKind::Punctuation(Punctuation::Hyphen))
265    }
266
267    /// Checks whether the token is whitespace.
268    pub fn is_whitespace(&self) -> bool {
269        matches!(self, TokenKind::Space(_) | TokenKind::Newline(_))
270    }
271
272    pub fn is_upos(&self, upos: UPOS) -> bool {
273        let Some(Some(meta)) = self.as_word() else {
274            return false;
275        };
276
277        meta.pos_tag == Some(upos)
278    }
279
280    // Miscellaneous non-is methods
281
282    /// Checks that `self` is the same enum variant as `other`, regardless of
283    /// whether the inner metadata is also equal.
284    pub fn matches_variant_of(&self, other: &Self) -> bool {
285        self.with_default_data() == other.with_default_data()
286    }
287
288    /// Produces a copy of `self` with any inner data replaced with its default
289    /// value. Useful for making comparisons on just the variant of the
290    /// enum.
291    pub fn with_default_data(&self) -> Self {
292        match self {
293            TokenKind::Word(_) => TokenKind::Word(Default::default()),
294            TokenKind::Punctuation(_) => TokenKind::Punctuation(Default::default()),
295            TokenKind::Number(..) => TokenKind::Number(Default::default()),
296            TokenKind::Space(_) => TokenKind::Space(Default::default()),
297            TokenKind::Newline(_) => TokenKind::Newline(Default::default()),
298            _ => self.clone(),
299        }
300    }
301
302    /// Construct a [`TokenKind::Word`] with no metadata.
303    pub fn blank_word() -> Self {
304        Self::Word(None)
305    }
306
307    // Punctuation and symbol non-is methods
308
309    pub fn as_mut_quote(&mut self) -> Option<&mut Quote> {
310        self.as_mut_punctuation()?.as_mut_quote()
311    }
312
313    pub fn as_quote(&self) -> Option<&Quote> {
314        self.as_punctuation()?.as_quote()
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use crate::Document;
321
322    #[test]
323    fn car_is_singular_noun() {
324        let doc = Document::new_plain_english_curated("car");
325        let tk = &doc.tokens().next().unwrap().kind;
326        assert!(tk.is_singular_noun());
327    }
328
329    #[test]
330    fn traffic_is_mass_noun_only() {
331        let doc = Document::new_plain_english_curated("traffic");
332        let tk = &doc.tokens().next().unwrap().kind;
333        assert!(tk.is_mass_noun_only());
334    }
335
336    #[test]
337    fn equipment_is_mass_noun() {
338        let doc = Document::new_plain_english_curated("equipment");
339        let tk = &doc.tokens().next().unwrap().kind;
340        assert!(tk.is_mass_noun());
341    }
342
343    #[test]
344    fn equipment_is_non_countable_noun() {
345        let doc = Document::new_plain_english_curated("equipment");
346        let tk = &doc.tokens().next().unwrap().kind;
347        assert!(tk.is_non_countable_noun());
348    }
349
350    #[test]
351    fn equipment_isnt_countable_noun() {
352        let doc = Document::new_plain_english_curated("equipment");
353        let tk = &doc.tokens().next().unwrap().kind;
354        assert!(!tk.is_countable_noun());
355    }
356}