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_first_person_singular_pronoun,
80        is_first_person_plural_pronoun,
81        is_second_person_pronoun,
82        is_third_person_pronoun,
83        is_third_person_singular_pronoun,
84        is_third_person_plural_pronoun,
85        is_object_pronoun,
86        is_possessive_noun,
87        is_possessive_pronoun,
88
89        // Verb methods
90        is_verb,
91        is_auxiliary_verb,
92        is_linking_verb,
93        is_verb_lemma,
94        is_verb_past_form,
95        is_verb_progressive_form,
96        is_verb_third_person_singular_present_form,
97
98        // Adjective methods
99        is_adjective,
100        is_comparative_adjective,
101        is_superlative_adjective,
102        is_positive_adjective,
103
104        // Adverb methods
105        is_adverb,
106
107        // Determiner methods
108        is_determiner,
109        is_demonstrative_determiner,
110        is_possessive_determiner,
111        is_quantifier,
112        is_non_quantifier_determiner,
113
114        // Conjunction methods
115        is_conjunction,
116
117        // Generic word methods
118        is_swear,
119        is_likely_homograph,
120
121        // Orthography methods
122        is_lowercase,
123        is_titlecase,
124        is_allcaps,
125        is_lower_camel,
126        is_upper_camel
127    }
128
129    // Word metadata delegation methods not generated by macro
130    pub fn is_preposition(&self) -> bool {
131        let Word(Some(metadata)) = self else {
132            return false;
133        };
134        metadata.preposition
135    }
136
137    pub fn is_common_word(&self) -> bool {
138        let Word(Some(metadata)) = self else {
139            return true;
140        };
141        metadata.common
142    }
143
144    /// Checks whether a word token is out-of-vocabulary (not found in the dictionary).
145    ///
146    /// Returns `true` if the token is a word that was not found in the dictionary,
147    /// `false` if the token is a word found in the dictionary or is not a word token.
148    pub fn is_oov(&self) -> bool {
149        matches!(self, TokenKind::Word(None))
150    }
151
152    // Punctuation and symbol is-methods
153
154    pub fn is_open_square(&self) -> bool {
155        matches!(self, TokenKind::Punctuation(Punctuation::OpenSquare))
156    }
157
158    pub fn is_close_square(&self) -> bool {
159        matches!(self, TokenKind::Punctuation(Punctuation::CloseSquare))
160    }
161
162    pub fn is_open_round(&self) -> bool {
163        matches!(self, TokenKind::Punctuation(Punctuation::OpenRound))
164    }
165
166    pub fn is_close_round(&self) -> bool {
167        matches!(self, TokenKind::Punctuation(Punctuation::CloseRound))
168    }
169
170    pub fn is_pipe(&self) -> bool {
171        matches!(self, TokenKind::Punctuation(Punctuation::Pipe))
172    }
173
174    pub fn is_currency(&self) -> bool {
175        matches!(self, TokenKind::Punctuation(Punctuation::Currency(..)))
176    }
177
178    pub fn is_ellipsis(&self) -> bool {
179        matches!(self, TokenKind::Punctuation(Punctuation::Ellipsis))
180    }
181
182    pub fn is_hyphen(&self) -> bool {
183        matches!(self, TokenKind::Punctuation(Punctuation::Hyphen))
184    }
185
186    pub fn is_quote(&self) -> bool {
187        matches!(self, TokenKind::Punctuation(Punctuation::Quote(_)))
188    }
189
190    pub fn is_apostrophe(&self) -> bool {
191        matches!(self, TokenKind::Punctuation(Punctuation::Apostrophe))
192    }
193
194    pub fn is_period(&self) -> bool {
195        matches!(self, TokenKind::Punctuation(Punctuation::Period))
196    }
197
198    pub fn is_at(&self) -> bool {
199        matches!(self, TokenKind::Punctuation(Punctuation::At))
200    }
201
202    pub fn is_comma(&self) -> bool {
203        matches!(self, TokenKind::Punctuation(Punctuation::Comma))
204    }
205
206    pub fn is_semicolon(&self) -> bool {
207        matches!(self, TokenKind::Punctuation(Punctuation::Semicolon))
208    }
209
210    // Miscellaneous is-methods
211
212    /// Checks whether a token is word-like--meaning it is more complex than punctuation and can
213    /// hold semantic meaning in the way a word does.
214    pub fn is_word_like(&self) -> bool {
215        matches!(
216            self,
217            TokenKind::Word(..)
218                | TokenKind::EmailAddress
219                | TokenKind::Hostname
220                | TokenKind::Decade
221                | TokenKind::Number(..)
222        )
223    }
224
225    pub(crate) fn is_chunk_terminator(&self) -> bool {
226        if self.is_sentence_terminator() {
227            return true;
228        }
229
230        match self {
231            TokenKind::Punctuation(punct) => {
232                matches!(
233                    punct,
234                    Punctuation::Comma | Punctuation::Quote { .. } | Punctuation::Colon
235                )
236            }
237            _ => false,
238        }
239    }
240
241    pub(crate) fn is_sentence_terminator(&self) -> bool {
242        match self {
243            TokenKind::Punctuation(punct) => [
244                Punctuation::Period,
245                Punctuation::Bang,
246                Punctuation::Question,
247            ]
248            .contains(punct),
249            TokenKind::ParagraphBreak => true,
250            _ => false,
251        }
252    }
253
254    /// Used by `crate::parsers::CollapseIdentifiers`
255    /// TODO: Separate this into two functions and add OR functionality to
256    /// pattern matching
257    pub fn is_case_separator(&self) -> bool {
258        matches!(self, TokenKind::Punctuation(Punctuation::Underscore))
259            || matches!(self, TokenKind::Punctuation(Punctuation::Hyphen))
260    }
261
262    /// Checks whether the token is whitespace.
263    pub fn is_whitespace(&self) -> bool {
264        matches!(self, TokenKind::Space(_) | TokenKind::Newline(_))
265    }
266
267    pub fn is_upos(&self, upos: UPOS) -> bool {
268        let Some(Some(meta)) = self.as_word() else {
269            return false;
270        };
271
272        meta.pos_tag == Some(upos)
273    }
274
275    // Miscellaneous non-is methods
276
277    /// Checks that `self` is the same enum variant as `other`, regardless of
278    /// whether the inner metadata is also equal.
279    pub fn matches_variant_of(&self, other: &Self) -> bool {
280        self.with_default_data() == other.with_default_data()
281    }
282
283    /// Produces a copy of `self` with any inner data replaced with its default
284    /// value. Useful for making comparisons on just the variant of the
285    /// enum.
286    pub fn with_default_data(&self) -> Self {
287        match self {
288            TokenKind::Word(_) => TokenKind::Word(Default::default()),
289            TokenKind::Punctuation(_) => TokenKind::Punctuation(Default::default()),
290            TokenKind::Number(..) => TokenKind::Number(Default::default()),
291            TokenKind::Space(_) => TokenKind::Space(Default::default()),
292            TokenKind::Newline(_) => TokenKind::Newline(Default::default()),
293            _ => self.clone(),
294        }
295    }
296
297    /// Construct a [`TokenKind::Word`] with no metadata.
298    pub fn blank_word() -> Self {
299        Self::Word(None)
300    }
301
302    // Punctuation and symbol non-is methods
303
304    pub fn as_mut_quote(&mut self) -> Option<&mut Quote> {
305        self.as_mut_punctuation()?.as_mut_quote()
306    }
307
308    pub fn as_quote(&self) -> Option<&Quote> {
309        self.as_punctuation()?.as_quote()
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use crate::Document;
316
317    #[test]
318    fn car_is_singular_noun() {
319        let doc = Document::new_plain_english_curated("car");
320        let tk = &doc.tokens().next().unwrap().kind;
321        assert!(tk.is_singular_noun());
322    }
323
324    #[test]
325    fn traffic_is_mass_noun_only() {
326        let doc = Document::new_plain_english_curated("traffic");
327        let tk = &doc.tokens().next().unwrap().kind;
328        assert!(tk.is_mass_noun_only());
329    }
330
331    #[test]
332    fn equipment_is_mass_noun() {
333        let doc = Document::new_plain_english_curated("equipment");
334        let tk = &doc.tokens().next().unwrap().kind;
335        assert!(tk.is_mass_noun());
336    }
337
338    #[test]
339    fn equipment_is_non_countable_noun() {
340        let doc = Document::new_plain_english_curated("equipment");
341        let tk = &doc.tokens().next().unwrap().kind;
342        assert!(tk.is_non_countable_noun());
343    }
344
345    #[test]
346    fn equipment_isnt_countable_noun() {
347        let doc = Document::new_plain_english_curated("equipment");
348        let tk = &doc.tokens().next().unwrap().kind;
349        assert!(!tk.is_countable_noun());
350    }
351}