Skip to main content

harper_core/
indefinite_article.rs

1use std::borrow::Cow;
2
3use itertools::Itertools;
4
5use crate::case::Case::Upper;
6use crate::char_ext::CharExt;
7use crate::{CaseIterExt, Dialect};
8
9#[derive(PartialEq)]
10pub enum InitialSound {
11    Vowel,
12    Consonant,
13    Either, // for SQL
14}
15
16/// Checks whether a provided word begins with a vowel _sound_. Returns `None` if `word` is empty.
17///
18/// It was produced through trial and error.
19/// Matches with 99.71% and 99.77% of vowels and non-vowels in the
20/// Carnegie-Mellon University word -> pronunciation dataset.
21pub fn starts_with_vowel(word: &[char], dialect: Dialect) -> Option<InitialSound> {
22    if word.is_empty() {
23        return None;
24    }
25
26    if matches!(word, ['L', 'E', 'D'] | ['S', 'Q', 'L'] | ['U', 'R', 'L']) {
27        return Some(InitialSound::Either);
28    }
29
30    // Try to get the first chunk of a word that appears to be a partial initialism.
31    // For example:
32    // - `RFL` from `RFLink`
33    // - `m` from `mDNS`
34    let word = {
35        let word_casing = word.get_casing_unfiltered();
36        match word_casing.as_slice() {
37            // Lower-upper or upper-upper, possibly a (partial) initialism.
38            [Some(first_char_case), Some(Upper), ..] => {
39                &word[0..word_casing
40                    .iter()
41                    .position(|c| *c != Some(*first_char_case))
42                    .unwrap_or(word.len())]
43            }
44            // Lower-lower or upper-lower, unlikely to be a partial initialism.
45            _ => word,
46        }
47    };
48
49    let is_likely_initialism = word.iter().all(|c| !c.is_alphabetic() || c.is_uppercase());
50
51    if word.len() == 1 || (is_likely_initialism && !is_likely_acronym(word)) {
52        return Some(
53            if matches!(
54                word[0].to_ascii_uppercase(),
55                'A' | 'E' | 'F' | 'H' | 'I' | 'L' | 'M' | 'N' | 'O' | 'R' | 'S' | 'X'
56            ) {
57                InitialSound::Vowel
58            } else {
59                InitialSound::Consonant
60            },
61        );
62    }
63
64    let word = to_lower_word(word);
65    let word = word.as_ref();
66
67    if matches!(word, ['u', 'b', 'i', ..]) {
68        return Some(InitialSound::Either);
69    }
70
71    // Treat formats like `mp3` the same as `MP3`: the leading `m` is read as
72    // the letter name “em”, so it takes `an` rather than `a`.
73    if matches!(word, ['m', 'p', digit, ..] if digit.is_ascii_digit()) {
74        return Some(InitialSound::Vowel);
75    }
76
77    if matches!(word, ['e', 'u', 'l', 'e', ..]) {
78        return Some(InitialSound::Vowel);
79    }
80
81    if matches!(
82        word,
83        ['u', 'k', ..]
84            | ['u', 'd', 'e', ..] // for 'udev'
85            | ['e', 'u', 'p', 'h', ..]
86            | ['e', 'u', 'g' | 'l' | 'c', ..]
87            | ['o', 'n', 'e', ..]
88            | ['o', 'n', 'c', 'e']
89    ) {
90        return Some(InitialSound::Consonant);
91    }
92
93    if matches!(
94        word,
95        ['h', 'o', 'u', 'r', ..]
96            | ['u', 'n', 'i', 'n' | 'm', ..]
97            | ['u', 'n', 'a' | 'u', ..]
98            | ['u', 'r', 'b', ..]
99            | ['i', 'n', 't', ..]
100    ) {
101        return Some(InitialSound::Vowel);
102    }
103
104    if matches!(word, ['h', 'e', 'r', 'b', ..] if dialect == Dialect::American || dialect == Dialect::Canadian)
105    {
106        return Some(InitialSound::Vowel);
107    }
108
109    if matches!(word, ['u', 'n' | 's', 'i' | 'a' | 'u', ..]) {
110        return Some(InitialSound::Consonant);
111    }
112
113    if matches!(word, ['u', 'n', ..]) {
114        return Some(InitialSound::Vowel);
115    }
116
117    if matches!(word, ['u', 'r', 'g', ..]) {
118        return Some(InitialSound::Vowel);
119    }
120
121    if matches!(word, ['u', 't', 't', ..]) {
122        return Some(InitialSound::Vowel);
123    }
124
125    if matches!(
126        word,
127        ['u', 't' | 'r' | 'n', ..] | ['e', 'u', 'r', ..] | ['u', 'w', ..] | ['u', 's', 'e', ..]
128    ) {
129        return Some(InitialSound::Consonant);
130    }
131
132    if matches!(word, ['o', 'n', 'e', 'a' | 'e' | 'i' | 'u', 'l' | 'd', ..]) {
133        return Some(InitialSound::Vowel);
134    }
135
136    if matches!(word, ['o', 'n', 'e', 'a' | 'e' | 'i' | 'u' | '-' | 's', ..]) {
137        return Some(InitialSound::Consonant);
138    }
139
140    if matches!(
141        word,
142        ['s', 'o', 's']
143            | ['r', 'z', ..]
144            | ['n', 'g', ..]
145            | ['n', 'v', ..]
146            | ['x', 'b', 'o', 'x']
147            | ['h', 'e', 'i', 'r', ..]
148            | ['h', 'o', 'n', 'o', 'r', ..]
149            | ['h', 'o', 'n', 'e', 's', ..]
150    ) {
151        return Some(InitialSound::Vowel);
152    }
153
154    if matches!(
155        word,
156        ['j', 'u' | 'o', 'n', ..] | ['j', 'u', 'r', 'a' | 'i' | 'o', ..]
157    ) {
158        return Some(InitialSound::Consonant);
159    }
160
161    if matches!(word, ['x', '-' | '\'' | '.' | 'o' | 's', ..]) {
162        return Some(InitialSound::Vowel);
163    }
164
165    if word[0].is_vowel() {
166        return Some(InitialSound::Vowel);
167    }
168
169    Some(InitialSound::Consonant)
170}
171
172fn to_lower_word(word: &[char]) -> Cow<'_, [char]> {
173    if word.iter().any(|c| c.is_uppercase()) {
174        Cow::Owned(
175            word.iter()
176                .flat_map(|c| c.to_lowercase())
177                .collect::<Vec<_>>(),
178        )
179    } else {
180        Cow::Borrowed(word)
181    }
182}
183
184fn is_likely_acronym(word: &[char]) -> bool {
185    /// Does the word contain any sequences that might indicate it's not an acronym?
186    fn word_contains_false_positive_sequence(word: &[char]) -> bool {
187        let likely_false_positive_sequences = [['V', 'C']];
188        for fp_sequence in likely_false_positive_sequences {
189            if word
190                .windows(fp_sequence.len())
191                .any(|subslice| subslice == fp_sequence)
192            {
193                return true;
194            }
195        }
196        false
197    }
198
199    // If the initialism is shorter than this, skip it.
200    const MIN_LEN: usize = 3;
201
202    if let Some(first_chars) = word.get(..MIN_LEN)
203        // Unlikely to be an acronym if it contains non-alphabetic characters.
204        && first_chars.iter().copied().all(char::is_alphabetic)
205        && !word_contains_false_positive_sequence(word)
206    {
207        let vowel_map = first_chars
208            .iter()
209            .map(CharExt::is_vowel)
210            .collect_array::<MIN_LEN>()
211            .unwrap();
212        matches!(vowel_map, [false, true, false] | [false, true, true])
213    } else {
214        false
215    }
216}