1use std::collections::HashMap;
2use std::sync::LazyLock;
3
4use fancy_regex::Regex;
5
6use crate::data::*;
7use crate::text::{
8 capitalize, captures, char_len, chop, ends_with_any, group, is_match, last_char, regex,
9 slice_from_end, starts_upper, upper, Words,
10};
11use crate::{Classical, Comparison, Count, Error, Gender, JoinOptions};
12
13static PARTITION_WORD: LazyLock<Regex> = LazyLock::new(|| regex(r"\A(\s*)(.+?)(\s*)\z"));
14static PL_SB_POSTFIX_ADJ_STEMS_RE: LazyLock<Regex> =
15 LazyLock::new(|| regex(&format!("(?i)^(?:{})$", *PL_SB_POSTFIX_ADJ_STEMS)));
16static PL_SB_PREP_DUAL_COMPOUND_RE: LazyLock<Regex> =
17 LazyLock::new(|| regex(&format!("(?i)^(?:{})$", *PL_SB_PREP_DUAL_COMPOUND)));
18static DENOMINATOR: LazyLock<Regex> = LazyLock::new(|| regex(r"(?P<denominator>.+)( (per|a) .+)"));
19static PLVERB_SPECIAL_S_RE: LazyLock<Regex> =
20 LazyLock::new(|| regex(&format!("^({})$", *PLVERB_SPECIAL_S)));
21static PLVERB_AMBIGUOUS_PRES_RE: LazyLock<Regex> = LazyLock::new(|| {
22 regex(&format!(
23 r"(?i)^({})((\s.*)?)$",
24 *PLVERB_AMBIGUOUS_PRES_KEYS
25 ))
26});
27static ENDS_WITH_S: LazyLock<Regex> = LazyLock::new(|| regex(r"(?i)^(.*[^s])s$"));
28static ENDS_WITH_APOSTROPHE_S: LazyLock<Regex> = LazyLock::new(|| regex(r"^(.+)'s?$"));
29static INDEFINITE_ARTICLE_TEST: LazyLock<Regex> =
30 LazyLock::new(|| regex(r"(?i)\A(\s*)(?:an?\s+)?(.+?)(\s*)\z"));
31
32static INDEF_ARTICLE_CASES: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
33 [
34 (r"(?i)^([bcdgjkpqtuvwyz]-?th)", "a"),
35 (r"(?i)^([aefhilmnorsx]-?th)", "an"),
36 (r"(?i)^((?:euler|hour(?!i)|heir|honest|hono[ur]|mpeg))", "an"),
37 (r"(?i)^[aefhilmnorsx]$", "an"),
38 (r"(?i)^[bcdgjkpqtuvwyz]$", "a"),
39 (
40 r"^(?!FJO|[HLMNS]Y.|RY[EO]|SQU|(F[LR]?|[HL]|MN?|N|RH?|S[CHKLMNPTVW]?|X(YL)?)[AEIOU])[FHLMNRSX][A-Z]",
41 "an",
42 ),
43 (r"(?i)^[aefhilmnorsx][.-]", "an"),
44 (r"(?i)^[a-z][.-]", "a"),
45 (r"(?i)^[^aeiouy]", "a"),
46 (r"(?i)^e[uw]", "a"),
47 (r"(?i)^onc?e\b", "a"),
48 (r"(?i)^onetime\b", "a"),
49 (r"(?i)^uni([^nmd]|mo)", "a"),
50 (r"(?i)^u[bcfghjkqrst][aeiou]", "a"),
51 (r"(?i)^ukr", "a"),
52 (r"(?i)^((?:unabomber|unanimous|US))", "a"),
53 (r"^U[NK][AIEO]?", "a"),
54 (r"(?i)^[aeiou]", "an"),
55 (r"(?i)^(y(b[lor]|cl[ea]|fere|gg|p[ios]|rou|tt))", "an"),
56 ]
57 .into_iter()
58 .map(|(pattern, article)| (regex(pattern), article))
59 .collect()
60});
61
62static PRESENT_PARTICIPLE_REPLACEMENTS: LazyLock<Vec<(Regex, &'static str)>> =
63 LazyLock::new(|| {
64 [
65 (r"ie$", "y"),
66 (r"ue$", "u"),
67 (r"([auy])e$", "${1}"),
68 (r"ski$", "ski"),
69 (r"[^b]i$", ""),
70 (r"^(are|were)$", "be"),
71 (r"^(had)$", "hav"),
72 (r"^(hoe)$", "${1}"),
73 (r"([^e])e$", "${1}"),
74 (r"er$", "er"),
75 (r"([^aeiou][aeiouy]([bdgmnprst]))$", "${1}${2}"),
76 ]
77 .into_iter()
78 .map(|(pattern, replacement)| (regex(pattern), replacement))
79 .collect()
80 });
81
82static PLURAL_STEM_ENDINGS: LazyLock<Vec<(Regex, &'static str, &'static str)>> =
83 LazyLock::new(|| {
84 [
85 (C_A_ATA.stem.as_str(), "as", "ata"),
86 (PL_SB_C_IS_IDES.as_str(), "is", "ides"),
87 (C_A_AE.stem.as_str(), "s", "e"),
88 (C_EN_INA.stem.as_str(), "ens", "ina"),
89 (C_UM_A.stem.as_str(), "ums", "a"),
90 (C_US_I.stem.as_str(), "uses", "i"),
91 (C_ON_A.stem.as_str(), "ons", "a"),
92 (C_O_I.stem.as_str(), "os", "i"),
93 (C_EX_ICES.stem.as_str(), "exes", "ices"),
94 (C_IX_ICES.stem.as_str(), "ixes", "ices"),
95 (C_I.stem.as_str(), "s", "i"),
96 (C_IM.stem.as_str(), "s", "im"),
97 (".*eau", "s", "x"),
98 (".*ieu", "s", "x"),
99 (".*tri", "xes", "ces"),
100 (".{2,}[yia]n", "xes", "ges"),
101 ]
102 .into_iter()
103 .map(|(stems, end1, end2)| {
104 let pattern = format!(r"({stems})({end1}\|\1{end2}|{end2}\|\1{end1})");
105 (regex(&pattern), end1, end2)
106 })
107 .collect()
108 });
109
110enum SiPron {
111 Plain(&'static str),
112 Gendered([&'static str; 6]),
113}
114
115#[derive(Clone, Copy)]
116enum Case {
117 Nom,
118 Acc,
119}
120
121const THEMSELVES: [&str; 6] = [
122 "itself",
123 "herself",
124 "himself",
125 "themself",
126 "herself or himself",
127 "himself or herself",
128];
129
130fn invert_pronouns(pairs: &[(&'static str, &'static str)]) -> HashMap<&'static str, SiPron> {
131 pairs
132 .iter()
133 .map(|&(singular, plural)| (plural, SiPron::Plain(singular)))
134 .collect()
135}
136
137static SI_PRON_NOM: LazyLock<HashMap<&'static str, SiPron>> = LazyLock::new(|| {
138 let mut nom = invert_pronouns(PL_PRON_NOM);
139 nom.insert("we", SiPron::Plain("I"));
140 nom.insert(
141 "they",
142 SiPron::Gendered(["it", "she", "he", "they", "she or he", "he or she"]),
143 );
144 nom.insert("themselves", SiPron::Gendered(THEMSELVES));
145 nom.insert(
146 "theirs",
147 SiPron::Gendered(["its", "hers", "his", "theirs", "hers or his", "his or hers"]),
148 );
149 nom
150});
151
152static SI_PRON_ACC: LazyLock<HashMap<&'static str, SiPron>> = LazyLock::new(|| {
153 let mut acc = invert_pronouns(PL_PRON_ACC);
154 acc.insert(
155 "them",
156 SiPron::Gendered(["it", "her", "him", "them", "her or him", "him or her"]),
157 );
158 acc.insert("themselves", SiPron::Gendered(THEMSELVES));
159 acc
160});
161
162fn get_si_pron(case: Case, word: &str, gender: Gender) -> Option<&'static str> {
163 let table = match case {
164 Case::Nom => &*SI_PRON_NOM,
165 Case::Acc => &*SI_PRON_ACC,
166 };
167 table.get(word).map(|pron| match pron {
168 SiPron::Plain(s) => *s,
169 SiPron::Gendered(forms) => forms[gender as usize],
170 })
171}
172
173fn partition_word(text: &str) -> (&str, &str, &str) {
174 match captures(&PARTITION_WORD, text) {
175 Some(caps) => (group(&caps, 1), group(&caps, 2), group(&caps, 3)),
176 None => ("", "", ""),
177 }
178}
179
180fn prep_pronoun_split<'a>(words: &'a Words) -> Option<(&'a str, &'a str)> {
181 let lowered = words.lowered.as_str();
182 let mut tokens = lowered.split_whitespace();
183 let (prep, pronoun) = (tokens.next()?, tokens.next()?);
184 let exact = tokens.next().is_none()
185 && lowered.starts_with(prep)
186 && lowered.ends_with(pronoun)
187 && PL_PREP_SET.contains(prep);
188 exact.then_some((prep, pronoun))
189}
190
191#[derive(Clone, Copy, PartialEq, Eq)]
192enum Number {
193 One,
194 Many,
195 Unset,
196}
197
198const MANY: Count = Count::Num(2);
199const ONE: Count = Count::Num(1);
200
201#[derive(Clone, Copy, PartialEq, Eq)]
202enum PartOfSpeech {
203 Noun,
204 Verb,
205 Adjective,
206}
207
208#[derive(Clone, Debug)]
209struct UserDefined {
210 pattern: Regex,
211 replacement: String,
212}
213
214#[derive(Clone, Debug, Default)]
220pub struct Engine {
221 pub classical: Classical,
222 persistent_count: Option<i64>,
223 gender: Gender,
224 pl_sb_user_defined: Vec<UserDefined>,
225 pl_v_user_defined: Vec<UserDefined>,
226 pl_adj_user_defined: Vec<UserDefined>,
227 si_sb_user_defined: Vec<UserDefined>,
228 a_a_user_defined: Vec<UserDefined>,
229}
230
231fn user_defined(pattern: &str, replacement: &str) -> Result<UserDefined, Error> {
232 let compiled = Regex::new(&format!("(?i)^{pattern}$"))
233 .map_err(|_| Error::BadUserDefinedPattern(pattern.to_string()))?;
234 Ok(UserDefined {
235 pattern: compiled,
236 replacement: replacement.to_string(),
237 })
238}
239
240fn ud_match(word: &str, wordlist: &[UserDefined]) -> Option<String> {
241 wordlist.iter().rev().find_map(|ud| {
242 let caps = captures(&ud.pattern, word)?;
243 let mut expanded = String::new();
244 let mut rest = ud.replacement.as_str();
245 while let Some(pos) = rest.find('$') {
246 expanded.push_str(&rest[..pos]);
247 let after = &rest[pos + 1..];
248 let digits = after.len() - after.trim_start_matches(|c: char| c.is_ascii_digit()).len();
249 if digits == 0 {
250 expanded.push('$');
251 rest = after;
252 } else {
253 let index: usize = after[..digits].parse().unwrap_or(usize::MAX);
254 expanded.push_str(caps.get(index).map_or("", |m| m.as_str()));
255 rest = &after[digits..];
256 }
257 }
258 expanded.push_str(rest);
259 Some(expanded)
260 })
261}
262
263impl Engine {
264 pub fn new() -> Self {
265 Self::default()
266 }
267
268 pub fn defnoun(&mut self, singular: &str, plural: &str) -> Result<(), Error> {
272 self.pl_sb_user_defined
273 .push(user_defined(singular, plural)?);
274 self.si_sb_user_defined
275 .push(user_defined(plural, singular)?);
276 Ok(())
277 }
278
279 pub fn defverb(
281 &mut self,
282 s1: &str,
283 p1: &str,
284 s2: &str,
285 p2: &str,
286 s3: &str,
287 p3: &str,
288 ) -> Result<(), Error> {
289 let defs = [
290 user_defined(s1, p1)?,
291 user_defined(s2, p2)?,
292 user_defined(s3, p3)?,
293 ];
294 self.pl_v_user_defined.extend(defs);
295 Ok(())
296 }
297
298 pub fn defadj(&mut self, singular: &str, plural: &str) -> Result<(), Error> {
299 self.pl_adj_user_defined
300 .push(user_defined(singular, plural)?);
301 Ok(())
302 }
303
304 pub fn defa(&mut self, pattern: &str) -> Result<(), Error> {
306 self.a_a_user_defined.push(user_defined(pattern, "a")?);
307 Ok(())
308 }
309
310 pub fn defan(&mut self, pattern: &str) -> Result<(), Error> {
312 self.a_a_user_defined.push(user_defined(pattern, "an")?);
313 Ok(())
314 }
315
316 pub fn num(&mut self, count: Option<i64>) -> String {
319 self.persistent_count = count;
320 count.map(|n| n.to_string()).unwrap_or_default()
321 }
322
323 pub fn persistent_count(&self) -> Option<i64> {
324 self.persistent_count
325 }
326
327 pub fn set_gender(&mut self, gender: Gender) {
328 self.gender = gender;
329 }
330
331 pub fn gender(&self) -> Gender {
332 self.gender
333 }
334
335 fn postprocess(&self, orig: &str, inflected: &str) -> String {
336 let choice = usize::from(self.classical.all);
337 let mut result: Vec<String> = if inflected.contains('|') {
338 let options: Vec<&str> = inflected.split('|').collect();
339 if options[0].split(' ').count() == options[1].split(' ').count() {
340 options[choice].split(' ').map(String::from).collect()
341 } else {
342 inflected
343 .split(' ')
344 .map(|word| match word.split('|').nth(choice) {
345 Some(option) if word.contains('|') => option.to_string(),
346 _ => word.to_string(),
347 })
348 .collect()
349 }
350 } else {
351 inflected.split(' ').map(String::from).collect()
352 };
353
354 for (index, word) in orig.split(' ').enumerate() {
355 if word.is_empty() || word == "I" || index >= result.len() {
356 continue;
357 }
358 if capitalize(word) == word {
359 result[index] = capitalize(&result[index]);
360 }
361 if upper(word) == word {
362 result[index] = upper(&result[index]);
363 }
364 }
365 result.join(" ")
366 }
367
368 fn inflect_partitioned(&self, text: &str, inflect: impl FnOnce(&str) -> String) -> String {
369 let (pre, word, post) = partition_word(text);
370 if word.trim().is_empty() {
371 return text.to_string();
372 }
373 format!("{pre}{}{post}", self.postprocess(word, &inflect(word)))
374 }
375
376 pub fn plural(&self, text: &str) -> String {
380 self.plural_count(text, None)
381 }
382
383 pub fn plural_with_count(&self, text: &str, count: impl Into<Count>) -> String {
386 self.plural_count(text, Some(&count.into()))
387 }
388
389 pub(crate) fn plural_count(&self, text: &str, count: Option<&Count>) -> String {
390 self.inflect_partitioned(text, |word| {
391 self.pl_special_adjective(word, count)
392 .or_else(|| self.pl_special_verb(word, count))
393 .unwrap_or_else(|| self.plnoun(word, count))
394 })
395 }
396
397 pub fn plural_noun(&self, text: &str) -> String {
398 self.plural_noun_count(text, None)
399 }
400
401 pub fn plural_noun_with_count(&self, text: &str, count: impl Into<Count>) -> String {
402 self.plural_noun_count(text, Some(&count.into()))
403 }
404
405 pub(crate) fn plural_noun_count(&self, text: &str, count: Option<&Count>) -> String {
406 self.inflect_partitioned(text, |word| self.plnoun(word, count))
407 }
408
409 pub fn plural_verb(&self, text: &str) -> String {
410 self.plural_verb_count(text, None)
411 }
412
413 pub fn plural_verb_with_count(&self, text: &str, count: impl Into<Count>) -> String {
414 self.plural_verb_count(text, Some(&count.into()))
415 }
416
417 pub(crate) fn plural_verb_count(&self, text: &str, count: Option<&Count>) -> String {
418 self.inflect_partitioned(text, |word| {
419 self.pl_special_verb(word, count)
420 .unwrap_or_else(|| self.pl_general_verb(word, count))
421 })
422 }
423
424 pub fn plural_adj(&self, text: &str) -> String {
425 self.plural_adj_count(text, None)
426 }
427
428 pub fn plural_adj_with_count(&self, text: &str, count: impl Into<Count>) -> String {
429 self.plural_adj_count(text, Some(&count.into()))
430 }
431
432 pub(crate) fn plural_adj_count(&self, text: &str, count: Option<&Count>) -> String {
433 self.inflect_partitioned(text, |word| {
434 self.pl_special_adjective(word, count)
435 .unwrap_or_else(|| word.to_string())
436 })
437 }
438
439 pub fn singular_noun(&self, text: &str) -> Option<String> {
442 self.singular_noun_count(text, None, None)
443 }
444
445 pub fn singular_noun_with_count(&self, text: &str, count: impl Into<Count>) -> Option<String> {
446 self.singular_noun_count(text, Some(&count.into()), None)
447 }
448
449 pub fn singular_noun_with_gender(&self, text: &str, gender: Gender) -> Option<String> {
452 self.singular_noun_count(text, None, Some(gender))
453 }
454
455 pub(crate) fn singular_noun_count(
456 &self,
457 text: &str,
458 count: Option<&Count>,
459 gender: Option<Gender>,
460 ) -> Option<String> {
461 let (pre, word, post) = partition_word(text);
462 if word.trim().is_empty() {
463 return Some(text.to_string());
464 }
465 let singular = self.sinoun(word, count, gender.unwrap_or(self.gender))?;
466 Some(format!("{pre}{}{post}", self.postprocess(word, &singular)))
467 }
468
469 pub fn compare(&self, word1: &str, word2: &str) -> Option<Comparison> {
472 [
473 PartOfSpeech::Noun,
474 PartOfSpeech::Verb,
475 PartOfSpeech::Adjective,
476 ]
477 .into_iter()
478 .find_map(|pos| self.plequal(word1, word2, pos))
479 }
480
481 pub fn compare_nouns(&self, word1: &str, word2: &str) -> Option<Comparison> {
482 self.plequal(word1, word2, PartOfSpeech::Noun)
483 }
484
485 pub fn compare_verbs(&self, word1: &str, word2: &str) -> Option<Comparison> {
486 self.plequal(word1, word2, PartOfSpeech::Verb)
487 }
488
489 pub fn compare_adjs(&self, word1: &str, word2: &str) -> Option<Comparison> {
490 self.plequal(word1, word2, PartOfSpeech::Adjective)
491 }
492
493 fn plequal(&self, word1: &str, word2: &str, pos: PartOfSpeech) -> Option<Comparison> {
494 for classical in [Classical::all(), Classical::none()] {
495 let engine = Engine {
496 classical,
497 ..self.clone()
498 };
499 let pl = |word: &str| match pos {
500 PartOfSpeech::Noun => engine.plural_noun(word),
501 PartOfSpeech::Verb => engine.plural_verb(word),
502 PartOfSpeech::Adjective => engine.plural_adj(word),
503 };
504 if word1 == word2 {
505 return Some(Comparison::Eq);
506 }
507 if word1 == pl(word2) {
508 return Some(Comparison::PluralSingular);
509 }
510 if pl(word1) == word2 {
511 return Some(Comparison::SingularPlural);
512 }
513 }
514 let plurals = match pos {
515 PartOfSpeech::Noun => {
516 pl_check_plurals_n(word1, word2) || pl_check_plurals_n(word2, word1)
517 }
518 PartOfSpeech::Adjective => pl_check_plurals_adj(word1, word2),
519 PartOfSpeech::Verb => false,
520 };
521 plurals.then_some(Comparison::PluralPlural)
522 }
523
524 fn get_count(&self, count: Option<&Count>) -> Number {
525 let text = match (count, self.persistent_count) {
526 (Some(count), _) => count.to_string(),
527 (None, Some(n)) => n.to_string(),
528 (None, None) => return Number::Unset,
529 };
530 let zero = self.classical.zero && PL_COUNT_ZERO_SET.contains(text.to_lowercase().as_str());
531 if PL_COUNT_ONE_SET.contains(text.as_str()) || zero {
532 Number::One
533 } else {
534 Number::Many
535 }
536 }
537
538 fn plnoun(&self, word: &str, count: Option<&Count>) -> String {
539 if self.get_count(count) == Number::One {
540 return word.to_string();
541 }
542
543 if let Some(value) = ud_match(word, &self.pl_sb_user_defined) {
544 return value;
545 }
546
547 if word.is_empty() {
548 return String::new();
549 }
550
551 let words = Words::new(word);
552 let lowered = words.lowered.as_str();
553 let lowered_last = words.last.to_lowercase();
554 let lowered_last = lowered_last.as_str();
555
556 if PL_SB_UNINFLECTED_COMPLETE.contains(lowered_last) {
557 if words.split.len() >= 3 {
558 if let Some(handled) = self.handle_long_compounds(&words, Number::Many) {
559 return handled;
560 }
561 }
562 return word.to_string();
563 }
564
565 if PL_SB_UNINFLECTED_CAPS_SET.contains(word)
566 || ends_with_any(lowered, &PL_SB_UNINFLECTED_ENDINGS)
567 || (self.classical.herd && PL_SB_UNINFLECTED_HERD_SET.contains(lowered_last))
568 {
569 return word.to_string();
570 }
571
572 if let Some(caps) = captures(&PL_SB_POSTFIX_ADJ_STEMS_RE, word) {
573 if !group(&caps, 2).is_empty() {
574 return format!(
575 "{}{}",
576 self.plnoun(group(&caps, 1), Some(&MANY)),
577 group(&caps, 2)
578 );
579 }
580 }
581
582 if lowered.contains(" a ") || lowered.contains("-a-") {
583 if let Some(caps) = captures(&PL_SB_PREP_DUAL_COMPOUND_RE, word) {
584 if !group(&caps, 2).is_empty() && !group(&caps, 3).is_empty() {
585 return format!(
586 "{}{}{}",
587 self.plnoun(group(&caps, 1), Some(&MANY)),
588 group(&caps, 2),
589 self.plnoun(group(&caps, 3), None)
590 );
591 }
592 }
593 }
594
595 if words.split.len() >= 3 {
596 if let Some(handled) = self.handle_long_compounds(&words, Number::Many) {
597 return handled;
598 }
599 }
600
601 if let Some(caps) = captures(&DENOMINATOR, lowered) {
602 let index = char_len(group(&caps, 1));
603 let split = word
604 .char_indices()
605 .nth(index)
606 .map_or(word.len(), |(i, _)| i);
607 return format!("{}{}", self.plnoun(&word[..split], None), &word[split..]);
608 }
609
610 if words.split.len() >= 2 && words.split[words.split.len() - 2] == "degree" {
611 let rest = words.split[1..].iter().map(|s| s.to_string());
612 return std::iter::once(self.plnoun(words.first, None))
613 .chain(rest)
614 .collect::<Vec<_>>()
615 .join(" ");
616 }
617
618 if let Some(handled) =
619 handle_prepositional_phrase(lowered, '-', |part| Some(self.plnoun(part, Some(&MANY))))
620 {
621 return handled;
622 }
623
624 if let Some((_, pronoun)) = prep_pronoun_split(&words) {
625 if let Some(plural) = PL_PRON_ACC_MAP.get(pronoun) {
626 return format!("{}{plural}", chop(lowered, char_len(pronoun)));
627 }
628 }
629
630 if let Some(plural) = PL_PRON_NOM_MAP.get(lowered) {
631 return plural.to_string();
632 }
633 if let Some(plural) = PL_PRON_ACC_MAP.get(lowered) {
634 return plural.to_string();
635 }
636
637 if let Some(plural) = PL_SB_IRREGULAR_CAPS_MAP.get(words.last) {
638 return format!("{}{plural}", chop(word, char_len(words.last)));
639 }
640
641 if let Some(plural) = PL_SB_IRREGULAR.get(lowered_last) {
642 return format!("{}{plural}", chop(word, char_len(lowered_last)));
643 }
644
645 let compound = last_two_dash_parts(lowered);
646 if let Some(plural) = PL_SB_IRREGULAR_COMPOUND_MAP.get(compound.as_str()) {
647 return format!("{}{plural}", chop(word, char_len(&compound)));
648 }
649
650 if lowered.ends_with("quy") {
651 return format!("{}ies", chop(word, 1));
652 }
653
654 if lowered.ends_with("person") {
655 return if self.classical.persons {
656 format!("{word}s")
657 } else {
658 format!("{}ople", chop(word, 4))
659 };
660 }
661
662 if lowered.ends_with("man") {
663 if ends_with_any(lowered, PL_SB_U_MAN_MANS_LIST)
664 || ends_with_any(word, PL_SB_U_MAN_MANS_CAPS_LIST)
665 {
666 return format!("{word}s");
667 }
668 return format!("{}men", chop(word, 3));
669 }
670 if lowered.ends_with("mouse") {
671 return format!("{}mice", chop(word, 5));
672 }
673 if lowered.ends_with("louse") {
674 if PL_SB_U_LOUSE_LICE_LIST.contains(&lowered) {
675 return format!("{}lice", chop(word, 5));
676 }
677 return format!("{word}s");
678 }
679 if lowered.ends_with("goose") {
680 return format!("{}geese", chop(word, 5));
681 }
682 if lowered.ends_with("tooth") {
683 return format!("{}teeth", chop(word, 5));
684 }
685 if lowered.ends_with("foot") {
686 return format!("{}feet", chop(word, 4));
687 }
688 if lowered.ends_with("taco") {
689 return format!("{}tacos", chop(word, 4));
690 }
691
692 if lowered == "die" {
693 return "dice".to_string();
694 }
695
696 if lowered.ends_with("ceps") {
697 return word.to_string();
698 }
699 if lowered.ends_with("zoon") {
700 return format!("{}a", chop(word, 2));
701 }
702 if ["cis", "sis", "xis"].iter().any(|e| lowered.ends_with(e)) {
703 return format!("{}es", chop(word, 2));
704 }
705
706 let last = last_char(lowered);
707 let unassimilated: [(char, &[&str], usize, &str); 7] = [
708 ('h', PL_SB_U_CH_CHS_LIST, 0, "s"),
709 ('x', PL_SB_U_EX_ICES_LIST, 2, "ices"),
710 ('x', PL_SB_U_IX_ICES_LIST, 2, "ices"),
711 ('m', PL_SB_U_UM_A_LIST, 2, "a"),
712 ('s', PL_SB_U_US_I_LIST, 2, "i"),
713 ('n', PL_SB_U_ON_A_LIST, 2, "a"),
714 ('a', PL_SB_U_A_AE_LIST, 0, "e"),
715 ];
716 for (lastlet, list, numend, post) in unassimilated {
717 if last == Some(lastlet) && ends_with_any(lowered, list) {
718 return format!("{}{post}", chop(word, numend));
719 }
720 }
721
722 if self.classical.ancient {
723 if lowered.ends_with("trix") {
724 return format!("{}ces", chop(word, 1));
725 }
726 if lowered.ends_with("eau") || lowered.ends_with("ieu") {
727 return format!("{word}x");
728 }
729 if ["ynx", "inx", "anx"].iter().any(|e| lowered.ends_with(e)) && char_len(word) > 4 {
730 return format!("{}ges", chop(word, 1));
731 }
732
733 let incompletely_assimilated: [(Option<char>, &[&str], usize, &str); 13] = [
734 (Some('n'), PL_SB_C_EN_INA_LIST, 2, "ina"),
735 (Some('x'), PL_SB_C_EX_ICES_LIST, 2, "ices"),
736 (Some('x'), PL_SB_C_IX_ICES_LIST, 2, "ices"),
737 (Some('m'), PL_SB_C_UM_A_LIST, 2, "a"),
738 (Some('s'), PL_SB_C_US_I_LIST, 2, "i"),
739 (Some('s'), PL_SB_C_US_US, 0, ""),
740 (Some('a'), PL_SB_C_A_AE_LIST, 0, "e"),
741 (Some('a'), PL_SB_C_A_ATA_LIST, 0, "ta"),
742 (Some('s'), &PL_SB_C_IS_IDES_LIST, 1, "des"),
743 (Some('o'), PL_SB_C_O_I, 1, "i"),
744 (Some('n'), PL_SB_C_ON_A_LIST, 2, "a"),
745 (None, PL_SB_C_I_LIST, 0, "i"),
746 (None, PL_SB_C_IM_LIST, 0, "im"),
747 ];
748 for (lastlet, list, numend, post) in incompletely_assimilated {
749 if (lastlet.is_none() || last == lastlet) && ends_with_any(lowered, list) {
750 return format!("{}{post}", chop(word, numend));
751 }
752 }
753 }
754
755 if PL_SB_SINGULAR_S_COMPLETE.contains(&lowered_last)
756 || ends_with_any(lowered, &PL_SB_SINGULAR_S_ENDINGS)
757 || (lowered.ends_with("es") && starts_upper(word))
758 {
759 return format!("{word}es");
760 }
761
762 if last == Some('z') {
763 if ends_with_any(lowered, PL_SB_Z_ZES_LIST) {
764 return format!("{word}es");
765 }
766 if slice_from_end(lowered, 2, 1) != "z" {
767 return format!("{word}zes");
768 }
769 }
770
771 if lowered.ends_with("ze") && ends_with_any(lowered, PL_SB_ZE_ZES_LIST) {
772 return format!("{word}s");
773 }
774
775 if ["ch", "sh", "zz", "ss"]
776 .iter()
777 .any(|e| lowered.ends_with(e))
778 || last == Some('x')
779 {
780 return format!("{word}es");
781 }
782
783 if ["elf", "alf", "olf"].iter().any(|e| lowered.ends_with(e)) {
784 return format!("{}ves", chop(word, 1));
785 }
786 if lowered.ends_with("eaf") && slice_from_end(lowered, 4, 3) != "d" {
787 return format!("{}ves", chop(word, 1));
788 }
789 if ["nife", "life", "wife"]
790 .iter()
791 .any(|e| lowered.ends_with(e))
792 {
793 return format!("{}ves", chop(word, 2));
794 }
795 if lowered.ends_with("arf") {
796 return format!("{}ves", chop(word, 1));
797 }
798
799 if last == Some('y') {
800 if "aeiou".contains(slice_from_end(lowered, 2, 1)) || char_len(word) == 1 {
801 return format!("{word}s");
802 }
803 if self.classical.names && starts_upper(word) {
804 return format!("{word}s");
805 }
806 return format!("{}ies", chop(word, 1));
807 }
808
809 if PL_SB_U_O_OS_COMPLETE_SET.contains(lowered_last)
810 || ends_with_any(lowered, &PL_SB_U_O_OS_ENDINGS)
811 || ["ao", "eo", "io", "oo", "uo"]
812 .iter()
813 .any(|e| lowered.ends_with(e))
814 {
815 return format!("{word}s");
816 }
817
818 if last == Some('o') {
819 return format!("{word}es");
820 }
821
822 format!("{word}s")
823 }
824
825 fn handle_long_compounds(&self, words: &Words, number: Number) -> Option<String> {
826 let split = &words.split;
827 (0..split.len().saturating_sub(1)).find_map(|i| {
828 let (candidate, prep) = (split[i], split[i + 1]);
829 if !PL_PREP_SET.contains(prep) {
830 return None;
831 }
832 let inflected = if number == Number::One {
833 self.sinoun(candidate, Some(&ONE), self.gender)
834 .unwrap_or_else(|| candidate.to_string())
835 } else {
836 self.plnoun(candidate, Some(&MANY))
837 };
838 let parts: Vec<&str> = split[..i]
839 .iter()
840 .copied()
841 .chain([inflected.as_str(), prep])
842 .chain(split[i + 2..].iter().copied())
843 .collect();
844 Some(parts.join(" "))
845 })
846 }
847
848 fn pl_special_verb(&self, word: &str, count: Option<&Count>) -> Option<String> {
849 if self.classical.zero {
850 if let Some(count) = count {
851 if PL_COUNT_ZERO_SET.contains(count.to_string().to_lowercase().as_str()) {
852 return None;
853 }
854 }
855 }
856 if self.get_count(count) == Number::One {
857 return Some(word.to_string());
858 }
859
860 if let Some(value) = ud_match(word, &self.pl_v_user_defined) {
861 return Some(value).filter(|v| !v.is_empty());
862 }
863
864 let words = Words::new(word);
865 if words.split.is_empty() {
866 return None;
867 }
868 let first = words.first;
869 let after_first = &word[first.len()..];
870
871 if let Some(plural) = PLVERB_IRREGULAR_PRES_MAP.get(first) {
872 return Some(format!("{plural}{after_first}"));
873 }
874
875 if PLVERB_IRREGULAR_NON_PRES_SET.contains(first) {
876 return Some(word.to_string());
877 }
878
879 if let Some(stem) = first.strip_suffix("n't") {
880 if let Some(plural) = PLVERB_IRREGULAR_PRES_MAP.get(stem) {
881 return Some(format!("{plural}n't{after_first}"));
882 }
883 return Some(word.to_string());
884 }
885
886 if is_match(&PLVERB_SPECIAL_S_RE, word) || word.chars().any(char::is_whitespace) {
887 return None;
888 }
889
890 let lowered = words.lowered.as_str();
891 if lowered == "quizzes" {
892 return Some("quiz".to_string());
893 }
894
895 if ["ches", "shes", "zzes", "sses"]
896 .iter()
897 .any(|e| lowered.ends_with(e))
898 || lowered.ends_with("xes")
899 {
900 return Some(chop(word, 2).to_string());
901 }
902
903 if lowered.ends_with("ies") && char_len(word) > 3 {
904 return Some(format!("{}y", chop(lowered, 3)));
905 }
906
907 if PL_V_OES_OE_SET.contains(words.last.to_lowercase().as_str())
908 || ends_with_any(lowered, PL_V_OES_OE_ENDINGS_SIZE4)
909 || ends_with_any(lowered, PL_V_OES_OE_ENDINGS_SIZE5)
910 {
911 return Some(chop(word, 1).to_string());
912 }
913
914 if lowered.ends_with("oes") && char_len(word) > 3 {
915 return Some(chop(lowered, 2).to_string());
916 }
917
918 captures(&ENDS_WITH_S, word).map(|caps| group(&caps, 1).to_string())
919 }
920
921 fn pl_general_verb(&self, word: &str, count: Option<&Count>) -> String {
922 if self.get_count(count) == Number::One {
923 return word.to_string();
924 }
925
926 if let Some(caps) = captures(&PLVERB_AMBIGUOUS_PRES_RE, word) {
927 let key = group(&caps, 1).to_lowercase();
928 if let Some(plural) = PLVERB_AMBIGUOUS_PRES_MAP.get(key.as_str()) {
929 return format!("{plural}{}", group(&caps, 2));
930 }
931 }
932
933 word.to_string()
934 }
935
936 fn pl_special_adjective(&self, word: &str, count: Option<&Count>) -> Option<String> {
937 if self.get_count(count) == Number::One {
938 return Some(word.to_string());
939 }
940
941 if let Some(value) = ud_match(word, &self.pl_adj_user_defined) {
942 return Some(value).filter(|v| !v.is_empty());
943 }
944
945 let lowered = word.to_lowercase();
946 if let Some(plural) = PL_ADJ_SPECIAL_MAP.get(lowered.as_str()) {
947 return Some(plural.to_string());
948 }
949 if let Some(plural) = PL_ADJ_POSS_MAP.get(lowered.as_str()) {
950 return Some(plural.to_string());
951 }
952
953 let caps = captures(&ENDS_WITH_APOSTROPHE_S, word)?;
954 let plural = self.plural_noun(group(&caps, 1));
955 let trailing_s = if plural.ends_with('s') { "" } else { "s" };
956 Some(format!("{plural}'{trailing_s}"))
957 }
958
959 fn sinoun(&self, word: &str, count: Option<&Count>, gender: Gender) -> Option<String> {
960 if self.get_count(count) == Number::Many {
961 return Some(word.to_string());
962 }
963
964 if let Some(value) = ud_match(word, &self.si_sb_user_defined) {
965 return Some(value);
966 }
967
968 if word.is_empty() {
969 return Some(String::new());
970 }
971
972 if SI_SB_OIS_OI_CASE_SET.contains(word) {
973 return Some(chop(word, 1).to_string());
974 }
975
976 let words = Words::new(word);
977 let lowered = words.lowered.as_str();
978 let lowered_last = words.last.to_lowercase();
979 let lowered_last = lowered_last.as_str();
980 let unchanged = || Some(word.to_string());
981
982 if PL_SB_UNINFLECTED_COMPLETE.contains(lowered_last) {
983 if words.split.len() >= 3 {
984 if let Some(handled) = self.handle_long_compounds(&words, Number::One) {
985 return Some(handled);
986 }
987 }
988 return unchanged();
989 }
990
991 if PL_SB_UNINFLECTED_CAPS_SET.contains(word)
992 || ends_with_any(lowered, &PL_SB_UNINFLECTED_ENDINGS)
993 || (self.classical.herd && PL_SB_UNINFLECTED_HERD_SET.contains(lowered_last))
994 {
995 return unchanged();
996 }
997
998 if PL_SB_C_US_US_SET.contains(lowered_last) {
999 return if self.classical.ancient {
1000 unchanged()
1001 } else {
1002 None
1003 };
1004 }
1005
1006 if let Some(caps) = captures(&PL_SB_POSTFIX_ADJ_STEMS_RE, word) {
1007 if !group(&caps, 2).is_empty() {
1008 let head = group(&caps, 1);
1009 let singular = self
1010 .sinoun(head, Some(&ONE), gender)
1011 .unwrap_or_else(|| head.to_string());
1012 return Some(format!("{singular}{}", group(&caps, 2)));
1013 }
1014 }
1015
1016 for sep in [' ', '-'] {
1017 if let Some(handled) = handle_prepositional_phrase(lowered, sep, |part| {
1018 self.sinoun(part, Some(&ONE), gender)
1019 }) {
1020 return Some(handled);
1021 }
1022 }
1023
1024 if let Some((_, pronoun)) = prep_pronoun_split(&words) {
1025 if let Some(singular) = get_si_pron(Case::Acc, pronoun, gender) {
1026 return Some(format!("{}{singular}", chop(lowered, char_len(pronoun))));
1027 }
1028 }
1029
1030 if let Some(singular) = get_si_pron(Case::Nom, lowered, gender) {
1031 return Some(singular.to_string());
1032 }
1033 if let Some(singular) = get_si_pron(Case::Acc, lowered, gender) {
1034 return Some(singular.to_string());
1035 }
1036
1037 if let Some(singular) = SI_SB_IRREGULAR_CAPS.get(words.last) {
1038 return Some(format!("{}{singular}", chop(word, char_len(words.last))));
1039 }
1040
1041 if let Some(singular) = SI_SB_IRREGULAR.get(lowered_last) {
1042 return Some(format!("{}{singular}", chop(word, char_len(lowered_last))));
1043 }
1044
1045 let compound = last_two_dash_parts(lowered);
1046 if let Some(singular) = SI_SB_IRREGULAR_COMPOUND.get(compound.as_str()) {
1047 return Some(format!("{}{singular}", chop(word, char_len(&compound))));
1048 }
1049
1050 if lowered.ends_with("quies") {
1051 return Some(format!("{}y", chop(word, 3)));
1052 }
1053
1054 if lowered.ends_with("persons") {
1055 return Some(chop(word, 1).to_string());
1056 }
1057 if lowered.ends_with("people") {
1058 return Some(format!("{}rson", chop(word, 4)));
1059 }
1060
1061 if lowered.ends_with("mans")
1062 && (ends_with_any(lowered, &U_MAN_MANS.plurals)
1063 || ends_with_any(word, &U_MAN_MANS_CAPS.plurals))
1064 {
1065 return Some(chop(word, 1).to_string());
1066 }
1067 if lowered.ends_with("men") {
1068 return Some(format!("{}man", chop(word, 3)));
1069 }
1070 if lowered.ends_with("mice") {
1071 return Some(format!("{}mouse", chop(word, 4)));
1072 }
1073 if lowered.ends_with("lice") && U_LOUSE_LICE.plurals.iter().any(|p| p == lowered) {
1074 return Some(format!("{}louse", chop(word, 4)));
1075 }
1076 if lowered.ends_with("geese") {
1077 return Some(format!("{}goose", chop(word, 5)));
1078 }
1079 if lowered.ends_with("teeth") {
1080 return Some(format!("{}tooth", chop(word, 5)));
1081 }
1082 if lowered.ends_with("feet") {
1083 return Some(format!("{}foot", chop(word, 4)));
1084 }
1085
1086 if lowered == "dice" {
1087 return Some("die".to_string());
1088 }
1089
1090 if lowered.ends_with("ceps") {
1091 return unchanged();
1092 }
1093 if lowered.ends_with("zoa") {
1094 return Some(format!("{}on", chop(word, 1)));
1095 }
1096
1097 let last = last_char(lowered);
1098 let unassimilated: [(char, &[String], usize, &str); 7] = [
1099 ('s', &U_CH_CHS.plurals, 1, ""),
1100 ('s', &U_EX_ICES.plurals, 4, "ex"),
1101 ('s', &U_IX_ICES.plurals, 4, "ix"),
1102 ('a', &U_UM_A.plurals, 1, "um"),
1103 ('i', &U_US_I.plurals, 1, "us"),
1104 ('a', &U_ON_A.plurals, 1, "on"),
1105 ('e', &U_A_AE.plurals, 1, ""),
1106 ];
1107 for (lastlet, list, numend, post) in unassimilated {
1108 if last == Some(lastlet) && ends_with_any(lowered, list) {
1109 return Some(format!("{}{post}", chop(word, numend)));
1110 }
1111 }
1112
1113 if self.classical.ancient {
1114 if lowered.ends_with("trices") {
1115 return Some(format!("{}x", chop(word, 3)));
1116 }
1117 if lowered.ends_with("eaux") || lowered.ends_with("ieux") {
1118 return Some(chop(word, 1).to_string());
1119 }
1120 if ["ynges", "inges", "anges"]
1121 .iter()
1122 .any(|e| lowered.ends_with(e))
1123 && char_len(word) > 6
1124 {
1125 return Some(format!("{}x", chop(word, 3)));
1126 }
1127
1128 let c_us_us: Vec<String> = PL_SB_C_US_US.iter().map(|w| w.to_string()).collect();
1129 let incompletely_assimilated: [(char, &[String], usize, &str); 13] = [
1130 ('a', &C_EN_INA.plurals, 3, "en"),
1131 ('s', &C_EX_ICES.plurals, 4, "ex"),
1132 ('s', &C_IX_ICES.plurals, 4, "ix"),
1133 ('a', &C_UM_A.plurals, 1, "um"),
1134 ('i', &C_US_I.plurals, 1, "us"),
1135 ('s', &c_us_us, 0, ""),
1136 ('e', &C_A_AE.plurals, 1, ""),
1137 ('a', &C_A_ATA.plurals, 2, ""),
1138 ('s', &SI_SB_C_IS_IDES, 3, "s"),
1139 ('i', &C_O_I.plurals, 1, "o"),
1140 ('a', &C_ON_A.plurals, 1, "on"),
1141 ('m', &C_IM.plurals, 2, ""),
1142 ('i', &C_I.plurals, 1, ""),
1143 ];
1144 for (lastlet, list, numend, post) in incompletely_assimilated {
1145 if last == Some(lastlet) && ends_with_any(lowered, list) {
1146 return Some(format!("{}{post}", chop(word, numend)));
1147 }
1148 }
1149 }
1150
1151 if lowered.ends_with("houses")
1152 || SI_SB_USES_USE_CASE_SET.contains(word)
1153 || SI_SB_USES_USE_SET.contains(lowered_last)
1154 || SI_SB_IES_IE_CASE_SET.contains(word)
1155 || SI_SB_IES_IE_SET.contains(lowered_last)
1156 || lowered.ends_with("shoes")
1157 || SI_SB_OES_OE_CASE_SET.contains(word)
1158 || SI_SB_OES_OE_SET.contains(lowered_last)
1159 || SI_SB_SSES_SSE_CASE_SET.contains(word)
1160 || SI_SB_SSES_SSE_SET.contains(lowered_last)
1161 {
1162 return Some(chop(word, 1).to_string());
1163 }
1164
1165 if SI_SB_SINGULAR_S_COMPLETE.contains(lowered_last)
1166 || ends_with_any(lowered, &SI_SB_SINGULAR_S_ENDINGS)
1167 || (lowered.ends_with("eses") && starts_upper(word))
1168 || SI_SB_Z_ZES_SET.contains(lowered_last)
1169 || SI_SB_ZZES_ZZ_SET.contains(lowered_last)
1170 {
1171 return Some(chop(word, 2).to_string());
1172 }
1173
1174 if lowered.ends_with("zzes") {
1175 return Some(chop(word, 3).to_string());
1176 }
1177
1178 if SI_SB_CHES_CHE_CASE_SET.contains(word) || SI_SB_CHES_CHE_SET.contains(lowered_last) {
1179 return Some(chop(word, 1).to_string());
1180 }
1181 if lowered.ends_with("ches") || lowered.ends_with("shes") {
1182 return Some(chop(word, 2).to_string());
1183 }
1184
1185 if SI_SB_XES_XE_SET.contains(lowered_last) {
1186 return Some(chop(word, 1).to_string());
1187 }
1188 if lowered.ends_with("xes") {
1189 return Some(chop(word, 2).to_string());
1190 }
1191
1192 if SI_SB_VES_VE_CASE_SET.contains(word) || SI_SB_VES_VE_SET.contains(lowered_last) {
1193 return Some(chop(word, 1).to_string());
1194 }
1195
1196 if lowered.ends_with("ves") {
1197 let before = slice_from_end(lowered, 5, 3);
1198 if ["el", "al", "ol", "ar"].contains(&before)
1199 || (before == "ea" && slice_from_end(word, 6, 5) != "d")
1200 {
1201 return Some(format!("{}f", chop(word, 3)));
1202 }
1203 if ["ni", "li", "wi"].contains(&before) {
1204 return Some(format!("{}fe", chop(word, 3)));
1205 }
1206 }
1207
1208 if lowered.ends_with("ys") {
1209 let vowel_before = lowered
1210 .chars()
1211 .rev()
1212 .nth(2)
1213 .is_some_and(|c| "aeiou".contains(c));
1214 if vowel_before || (self.classical.names && starts_upper(word)) {
1215 return Some(chop(word, 1).to_string());
1216 }
1217 }
1218
1219 if lowered.ends_with("ies") {
1220 return Some(format!("{}y", chop(word, 3)));
1221 }
1222
1223 if lowered.ends_with("os")
1224 && (SI_SB_U_O_OS_COMPLETE.contains(lowered_last)
1225 || ends_with_any(lowered, &SI_SB_U_O_OS_ENDINGS)
1226 || ["aos", "eos", "ios", "oos", "uos"]
1227 .iter()
1228 .any(|e| lowered.ends_with(e)))
1229 {
1230 return Some(chop(word, 1).to_string());
1231 }
1232
1233 if lowered.ends_with("oes") {
1234 return Some(chop(word, 2).to_string());
1235 }
1236
1237 if SI_SB_ES_IS_SET.contains(word) {
1238 return Some(format!("{}is", chop(word, 2)));
1239 }
1240
1241 if last == Some('s') {
1242 return Some(chop(word, 1).to_string());
1243 }
1244
1245 None
1246 }
1247
1248 pub fn a(&self, text: &str) -> String {
1253 self.a_count(text, &ONE)
1254 }
1255
1256 pub fn an(&self, text: &str) -> String {
1257 self.a(text)
1258 }
1259
1260 pub fn a_with_count(&self, text: &str, count: impl Into<Count>) -> String {
1263 self.a_count(text, &count.into())
1264 }
1265
1266 fn a_count(&self, text: &str, count: &Count) -> String {
1267 let Some(caps) = captures(&INDEFINITE_ARTICLE_TEST, text) else {
1268 return String::new();
1269 };
1270 let (pre, word, post) = (group(&caps, 1), group(&caps, 2), group(&caps, 3));
1271 if word.is_empty() {
1272 return text.to_string();
1273 }
1274 format!("{pre}{}{post}", self.indef_article(word, count))
1275 }
1276
1277 fn indef_article(&self, word: &str, count: &Count) -> String {
1278 if self.get_count(Some(count)) != Number::One {
1279 return format!("{count} {word}");
1280 }
1281
1282 if let Some(article) = ud_match(word, &self.a_a_user_defined) {
1283 return format!("{article} {word}");
1284 }
1285
1286 let article = INDEF_ARTICLE_CASES
1287 .iter()
1288 .find(|(re, _)| is_match(re, word))
1289 .map_or("a", |&(_, article)| article);
1290 format!("{article} {word}")
1291 }
1292
1293 pub fn no(&self, text: &str) -> String {
1298 let count = Count::Num(self.persistent_count.unwrap_or(0));
1299 self.no_count(text, count)
1300 }
1301
1302 pub fn no_with_count(&self, text: &str, count: impl Into<Count>) -> String {
1303 self.no_count(text, count.into())
1304 }
1305
1306 fn no_count(&self, text: &str, count: Count) -> String {
1307 let (pre, word, post) = partition_word(text);
1308 let count = if PL_COUNT_ZERO_SET.contains(count.to_string().to_lowercase().as_str()) {
1309 Count::Word("no".to_string())
1310 } else {
1311 count
1312 };
1313 let plural = self.plural_count(word, Some(&count));
1314 format!("{pre}{count} {plural}{post}")
1315 }
1316
1317 pub fn present_participle(&self, word: &str) -> String {
1320 let plural = self.plural_verb_with_count(word, 2);
1321 let participle = PRESENT_PARTICIPLE_REPLACEMENTS
1322 .iter()
1323 .find(|(re, _)| is_match(re, &plural))
1324 .map_or_else(
1325 || plural.clone(),
1326 |(re, replacement)| re.replace_all(&plural, *replacement).into_owned(),
1327 );
1328 format!("{participle}ing")
1329 }
1330
1331 pub fn join(&self, words: &[&str]) -> String {
1333 self.join_with(words, &JoinOptions::default())
1334 }
1335
1336 pub fn join_with(&self, words: &[&str], options: &JoinOptions) -> String {
1337 match words {
1338 [] => return String::new(),
1339 [word] => return word.to_string(),
1340 _ => {}
1341 }
1342
1343 let conj = if !options.conj_spaced {
1344 options.conj.clone()
1345 } else if options.conj.is_empty() {
1346 " ".to_string()
1347 } else {
1348 format!(" {} ", options.conj)
1349 };
1350
1351 if let [first, second] = words {
1352 return format!("{first}{conj}{second}");
1353 }
1354
1355 let mut sep = options.sep.clone().unwrap_or_else(|| {
1356 if words.iter().any(|w| w.contains(',')) {
1357 ";".to_string()
1358 } else {
1359 ",".to_string()
1360 }
1361 });
1362 let final_sep = format!("{}{conj}", options.final_sep.as_ref().unwrap_or(&sep));
1363 if options.sep_spaced {
1364 sep.push(' ');
1365 }
1366
1367 let (last, init) = words.split_last().expect("at least three words");
1368 format!("{}{final_sep}{last}", init.join(&sep))
1369 }
1370}
1371
1372fn last_two_dash_parts(lowered: &str) -> String {
1373 let parts: Vec<&str> = lowered.split('-').collect();
1374 parts[parts.len().saturating_sub(2)..].join(" ")
1375}
1376
1377fn handle_prepositional_phrase(
1378 phrase: &str,
1379 sep: char,
1380 transform: impl FnOnce(&str) -> Option<String>,
1381) -> Option<String> {
1382 let parts: Vec<&str> = phrase.split(sep).collect();
1383 if parts.len() < 3 {
1384 return None;
1385 }
1386 let pivot = (1..parts.len() - 1).find(|&i| PL_PREP_SET.contains(parts[i]))?;
1387 let transformed = transform(parts[pivot - 1])
1388 .filter(|t| !t.is_empty())
1389 .unwrap_or_else(|| parts[pivot - 1].to_string());
1390 let sep = sep.to_string();
1391 let joined = [transformed.as_str(), parts[pivot], ""].join(&sep);
1392 let head: Vec<&str> = parts[..pivot - 1]
1393 .iter()
1394 .copied()
1395 .chain([joined.as_str()])
1396 .collect();
1397 Some(head.join(" ") + &parts[pivot + 1..].join(" "))
1398}
1399
1400fn pl_check_plurals_n(word1: &str, word2: &str) -> bool {
1401 let (last1, last2) = (Words::new(word1).last, Words::new(word2).last);
1402 let pair = format!("{last1}|{last2}");
1403 let single_separator = !last1.contains('|') && !last2.contains('|');
1404 PL_SB_IRREGULAR_VALUES.contains(pair.as_str())
1405 || PLURAL_STEM_ENDINGS.iter().any(|(re, end1, end2)| {
1406 let possible = !single_separator || last1.ends_with(end1) || last1.ends_with(end2);
1407 possible && is_match(re, &pair)
1408 })
1409}
1410
1411fn pl_check_plurals_adj(word1: &str, word2: &str) -> bool {
1412 let strip_possessive = |word: &str| -> String {
1413 if word.ends_with("'s") || word.ends_with('\'') {
1414 word[..word.rfind('\'').unwrap_or(0)].to_string()
1415 } else {
1416 String::new()
1417 }
1418 };
1419 let (word1, word2) = (strip_possessive(word1), strip_possessive(word2));
1420 !word1.is_empty()
1421 && !word2.is_empty()
1422 && (pl_check_plurals_n(&word1, &word2) || pl_check_plurals_n(&word2, &word1))
1423}
1424
1425#[cfg(test)]
1426mod tests {
1427 use super::*;
1428
1429 #[test]
1430 fn si_pron() {
1431 assert_eq!(
1432 get_si_pron(Case::Acc, "them", Gender::Masculine),
1433 Some("him")
1434 );
1435 assert_eq!(
1436 get_si_pron(Case::Acc, "them", Gender::Feminine),
1437 Some("her")
1438 );
1439 assert_eq!(get_si_pron(Case::Acc, "them", Gender::Neuter), Some("it"));
1440 assert_eq!(get_si_pron(Case::Acc, "you", Gender::Neuter), Some("you"));
1441 assert_eq!(get_si_pron(Case::Nom, "we", Gender::Neuter), Some("I"));
1442 assert_eq!(get_si_pron(Case::Acc, "itself", Gender::Neuter), None);
1443 }
1444
1445 #[test]
1446 fn prepositional_phrase() {
1447 let upper = |s: &str| Some(s.to_uppercase());
1448 assert_eq!(
1449 handle_prepositional_phrase("man-of-war", '-', upper).as_deref(),
1450 Some("MAN-of-war")
1451 );
1452 assert_eq!(
1453 handle_prepositional_phrase("man of war", ' ', upper).as_deref(),
1454 Some("MAN of war")
1455 );
1456 assert_eq!(handle_prepositional_phrase("man-war", '-', upper), None);
1457 }
1458
1459 #[test]
1460 fn long_compounds() {
1461 let e = Engine::new();
1462 let words = Words::new("pair of scissors");
1463 assert_eq!(
1464 e.handle_long_compounds(&words, Number::Many).as_deref(),
1465 Some("pairs of scissors")
1466 );
1467 let words = Words::new("men beyond hills");
1468 assert_eq!(
1469 e.handle_long_compounds(&words, Number::One).as_deref(),
1470 Some("man beyond hills")
1471 );
1472 }
1473
1474 #[test]
1475 fn user_defined_expansion() {
1476 let defs = [user_defined("(.*)x", "$1y$$2").unwrap()];
1477 assert_eq!(ud_match("box", &defs).as_deref(), Some("boy$"));
1478 assert_eq!(ud_match("cat", &defs), None);
1479 }
1480}