inflect-rs 0.26.0

inflect-rs is a Rust port of the Python inflect library, used to generate plurals, ordinals, indefinite articles, and to convert numbers to words.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use std::sync::LazyLock;

use fancy_regex::Regex;

use crate::text::{group, regex};
use crate::{Count, Engine, Error, Gender, NumberToWordsOptions};

static FUNCTION_CALL: LazyLock<Regex> = LazyLock::new(|| regex(r"((\w+)\([^)]*\)*)"));

const METHODS: &[(&str, &[&str])] = &[
    ("plural", &["text", "count"]),
    ("plural_adj", &["text", "count"]),
    ("plural_noun", &["text", "count"]),
    ("plural_verb", &["text", "count"]),
    ("singular_noun", &["text", "count", "gender"]),
    ("a", &["text", "count"]),
    ("an", &["text", "count"]),
    ("no", &["text", "count"]),
    ("ordinal", &["num"]),
    (
        "number_to_words",
        &[
            "num",
            "wantlist",
            "group",
            "comma",
            "andword",
            "zero",
            "one",
            "decimal",
            "threshold",
        ],
    ),
    ("present_participle", &["word"]),
    ("num", &["count", "show"]),
];

#[derive(Clone, Debug, PartialEq)]
enum Value {
    Str(String),
    Int(String),
    Float(String),
    Bool(bool),
    None,
    Tuple(Vec<Value>),
    List(Vec<Value>),
}

impl Value {
    fn repr(&self) -> String {
        match self {
            Value::Str(s) if s.contains('\'') && !s.contains('"') => {
                format!("\"{}\"", s.replace('\\', "\\\\"))
            }
            Value::Str(s) => format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'")),
            Value::Tuple(items) if items.len() == 1 => format!("({},)", items[0].repr()),
            Value::Tuple(items) => format!("({})", join_reprs(items)),
            Value::List(items) => format!("[{}]", join_reprs(items)),
            other => other.str(),
        }
    }

    fn str(&self) -> String {
        match self {
            Value::Str(s) | Value::Int(s) | Value::Float(s) => s.clone(),
            Value::Bool(true) => "True".to_string(),
            Value::Bool(false) => "False".to_string(),
            Value::None => "None".to_string(),
            other => other.repr(),
        }
    }

    fn truthy(&self) -> bool {
        match self {
            Value::Str(s) => !s.is_empty(),
            Value::Int(s) | Value::Float(s) => s.chars().any(|c| ('1'..='9').contains(&c)),
            Value::Bool(b) => *b,
            Value::None => false,
            Value::Tuple(items) | Value::List(items) => !items.is_empty(),
        }
    }
}

fn join_reprs(items: &[Value]) -> String {
    items.iter().map(Value::repr).collect::<Vec<_>>().join(", ")
}

type Call<'a> = (Vec<Value>, Vec<(&'a str, Value)>);

struct Parser<'a> {
    src: &'a str,
    pos: usize,
}

impl<'a> Parser<'a> {
    fn peek(&self) -> Option<char> {
        self.src[self.pos..].chars().next()
    }

    fn bump(&mut self) -> Option<char> {
        let c = self.peek()?;
        self.pos += c.len_utf8();
        Some(c)
    }

    fn skip_ws(&mut self) {
        while self.peek().is_some_and(char::is_whitespace) {
            self.bump();
        }
    }

    fn eat(&mut self, c: char) -> bool {
        self.skip_ws();
        if self.peek() == Some(c) {
            self.bump();
            true
        } else {
            false
        }
    }

    fn ident(&mut self) -> &'a str {
        let start = self.pos;
        while self.peek().is_some_and(|c| c.is_alphanumeric() || c == '_') {
            self.bump();
        }
        &self.src[start..self.pos]
    }

    fn string(&mut self, quote: char) -> Option<Value> {
        let mut s = String::new();
        loop {
            match self.bump()? {
                c if c == quote => return Some(Value::Str(s)),
                '\\' => match self.bump()? {
                    'n' => s.push('\n'),
                    't' => s.push('\t'),
                    c @ ('\\' | '\'' | '"') => s.push(c),
                    c => {
                        s.push('\\');
                        s.push(c);
                    }
                },
                c => s.push(c),
            }
        }
    }

    fn number(&mut self) -> Option<Value> {
        let start = self.pos;
        if self.peek() == Some('-') {
            self.bump();
        }
        while self
            .peek()
            .is_some_and(|c| c.is_ascii_digit() || c == '_' || c == '.')
        {
            self.bump();
        }
        let text = self.src[start..self.pos].replace('_', "");
        if text.is_empty() || text == "-" {
            return None;
        }
        Some(if text.contains('.') {
            Value::Float(text)
        } else {
            let negative = text.starts_with('-');
            let digits = text.trim_start_matches('-').trim_start_matches('0');
            let digits = if digits.is_empty() { "0" } else { digits };
            Value::Int(format!(
                "{}{digits}",
                if negative && digits != "0" { "-" } else { "" }
            ))
        })
    }

    fn sequence(&mut self, close: char) -> Option<(Vec<Value>, bool)> {
        let mut items = Vec::new();
        let mut trailing_comma = false;
        loop {
            if self.eat(close) {
                return Some((items, trailing_comma));
            }
            items.push(self.value()?);
            trailing_comma = self.eat(',');
            if !trailing_comma {
                return self.eat(close).then_some((items, false));
            }
        }
    }

    fn value(&mut self) -> Option<Value> {
        self.skip_ws();
        match self.peek()? {
            q @ ('\'' | '"') => {
                self.bump();
                self.string(q)
            }
            '(' => {
                self.bump();
                let (mut items, trailing_comma) = self.sequence(')')?;
                Some(if items.len() == 1 && !trailing_comma {
                    items.remove(0)
                } else {
                    Value::Tuple(items)
                })
            }
            '[' => {
                self.bump();
                Some(Value::List(self.sequence(']')?.0))
            }
            c if c.is_ascii_digit() || c == '-' || c == '.' => self.number(),
            _ => match self.ident() {
                "True" => Some(Value::Bool(true)),
                "False" => Some(Value::Bool(false)),
                "None" => Some(Value::None),
                _ => None,
            },
        }
    }

    fn call(&mut self) -> Option<Call<'a>> {
        self.ident();
        if !self.eat('(') {
            return None;
        }
        let mut args = Vec::new();
        let mut kwargs = Vec::new();
        loop {
            if self.eat(')') {
                break;
            }
            self.skip_ws();
            let checkpoint = self.pos;
            let name = self.ident();
            if !name.is_empty() && self.eat('=') {
                kwargs.push((name, self.value()?));
            } else {
                self.pos = checkpoint;
                if !kwargs.is_empty() {
                    return None;
                }
                args.push(self.value()?);
            }
            if !self.eat(',') {
                if !self.eat(')') {
                    return None;
                }
                break;
            }
        }
        self.skip_ws();
        (self.pos == self.src.len()).then_some((args, kwargs))
    }
}

fn bind(
    params: &[&str],
    args: Vec<Value>,
    kwargs: Vec<(&str, Value)>,
) -> Option<Vec<Option<Value>>> {
    if args.len() > params.len() {
        return None;
    }
    let mut bound: Vec<Option<Value>> = vec![None; params.len()];
    for (slot, arg) in bound.iter_mut().zip(args) {
        *slot = Some(arg);
    }
    for (name, value) in kwargs {
        let index = params.iter().position(|p| *p == name)?;
        if bound[index].replace(value).is_some() {
            return None;
        }
    }
    Some(bound)
}

impl Engine {
    /// Performs the inflections written as function calls inside `text`.
    ///
    /// `"The plural of cat is plural('cat')"` becomes
    /// `"The plural of cat is cats"`. The available functions are `plural`,
    /// `plural_noun`, `plural_verb`, `plural_adj`, `singular_noun`, `a`, `an`,
    /// `no`, `ordinal`, `number_to_words`, `present_participle` and `num`,
    /// taking the same arguments as the Python library.
    pub fn inflect(&mut self, text: &str) -> Result<String, Error> {
        let saved_count = self.persistent_count();
        let result = self.substitute_calls(text);
        self.num(saved_count);
        result
    }

    fn substitute_calls(&mut self, text: &str) -> Result<String, Error> {
        let mut out = String::with_capacity(text.len());
        let mut last = 0;
        for caps in FUNCTION_CALL.captures_iter(text) {
            let Ok(caps) = caps else { break };
            let whole = caps.get(0).expect("group 0 always matches");
            out.push_str(&text[last..whole.start()]);
            out.push_str(&self.substitute(group(&caps, 1), group(&caps, 2))?);
            last = whole.end();
        }
        out.push_str(&text[last..]);
        Ok(out)
    }

    fn substitute(&mut self, call: &str, name: &str) -> Result<String, Error> {
        let Some(&(_, params)) = METHODS.iter().find(|(method, _)| *method == name) else {
            return Ok(call.to_string());
        };
        let bad_call = || Error::BadInflectCall(call.to_string());
        let mut parser = Parser { src: call, pos: 0 };
        let (args, kwargs) = parser.call().ok_or_else(bad_call)?;
        let mut bound = bind(params, args, kwargs).ok_or_else(bad_call)?.into_iter();
        let mut next = || bound.next().flatten();

        let text = |value: Option<Value>| match value {
            Some(Value::Str(s)) if !s.is_empty() => Ok(s),
            _ => Err(bad_call()),
        };
        let count = |value: Option<Value>| match value {
            None | Some(Value::None) => None,
            Some(Value::Int(n)) => Some(n.parse().map_or(Count::Word(n), Count::Num)),
            Some(other) => Some(Count::Word(other.str())),
        };

        Ok(match name {
            "plural" | "plural_adj" | "plural_noun" | "plural_verb" => {
                let (word, count) = (text(next())?, count(next()));
                let count = count.as_ref();
                match name {
                    "plural" => self.plural_count(&word, count),
                    "plural_adj" => self.plural_adj_count(&word, count),
                    "plural_noun" => self.plural_noun_count(&word, count),
                    _ => self.plural_verb_count(&word, count),
                }
            }
            "singular_noun" => {
                let (word, count) = (text(next())?, count(next()));
                let gender = match next() {
                    None | Some(Value::None) => None,
                    Some(Value::Str(g)) => Some(g.parse::<Gender>()?),
                    Some(_) => return Err(bad_call()),
                };
                self.singular_noun_count(&word, count.as_ref(), gender)
                    .ok_or_else(bad_call)?
            }
            "a" | "an" => {
                let word = text(next())?;
                let count = match next() {
                    None => Count::Num(1),
                    Some(value) => count(Some(value)).unwrap_or(Count::Word("None".into())),
                };
                self.a_with_count(&word, count)
            }
            "no" => {
                let word = text(next())?;
                match count(next()) {
                    Some(count) => self.no_with_count(&word, count),
                    None => self.no(&word),
                }
            }
            "ordinal" => match next() {
                Some(Value::Str(s)) if !s.is_empty() => self.ordinal(s),
                Some(n @ (Value::Int(_) | Value::Float(_))) => self.ordinal(n.str()),
                _ => return Err(bad_call()),
            },
            "number_to_words" => {
                let num = match next() {
                    Some(Value::Str(s)) if !s.is_empty() => s,
                    Some(n @ (Value::Int(_) | Value::Float(_))) => n.str(),
                    _ => return Err(bad_call()),
                };
                if next().is_some_and(|wantlist| wantlist.truthy()) {
                    return Err(bad_call());
                }
                let defaults = NumberToWordsOptions::default();
                let string_or = |value: Option<Value>, default: String| match value {
                    None => Ok(default),
                    Some(Value::Str(s)) => Ok(s),
                    Some(_) => Err(bad_call()),
                };
                let options = NumberToWordsOptions {
                    group: match next() {
                        None => 0,
                        Some(Value::Int(n)) => n.parse().map_err(|_| Error::BadChunkingOption)?,
                        Some(_) => return Err(bad_call()),
                    },
                    comma: match next() {
                        None => defaults.comma,
                        Some(Value::Str(s)) => s,
                        Some(Value::Bool(false) | Value::None) => String::new(),
                        Some(_) => return Err(bad_call()),
                    },
                    andword: string_or(next(), defaults.andword)?,
                    zero: string_or(next(), defaults.zero)?,
                    one: string_or(next(), defaults.one)?,
                    decimal: match next() {
                        None => defaults.decimal,
                        Some(Value::Str(s)) => Some(s),
                        Some(Value::Bool(false) | Value::None) => None,
                        Some(_) => return Err(bad_call()),
                    },
                    threshold: match next() {
                        None | Some(Value::None) => None,
                        Some(Value::Int(n)) => Some(n.parse().map_err(|_| bad_call())?),
                        Some(_) => return Err(bad_call()),
                    },
                };
                self.number_to_words_with(num, &options)?
            }
            "present_participle" => self.present_participle(&text(next())?),
            "num" => {
                let value = next();
                let show = next();
                let count = match &value {
                    None | Some(Value::None) => None,
                    Some(Value::Bool(b)) => Some(i64::from(*b)),
                    Some(Value::Float(f)) => Some(
                        f.parse::<f64>()
                            .map_err(|_| Error::BadNumValue(f.clone()))?
                            .trunc() as i64,
                    ),
                    Some(other) => {
                        let s = other.str();
                        Some(s.trim().parse().map_err(|_| Error::BadNumValue(s))?)
                    }
                };
                self.num(count);
                match (&value, show) {
                    (None | Some(Value::None), _) => String::new(),
                    (_, Some(show)) if show != Value::None && !show.truthy() => String::new(),
                    (Some(value), _) => value.str(),
                }
            }
            _ => unreachable!("method table and dispatch agree"),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(call: &str) -> Option<Call<'_>> {
        Parser { src: call, pos: 0 }.call()
    }

    #[test]
    fn parses_literals() {
        let (args, kwargs) = parse("f('a', 2, (1,), ['x'], None, andword='')").unwrap();
        assert_eq!(
            args,
            vec![
                Value::Str("a".into()),
                Value::Int("2".into()),
                Value::Tuple(vec![Value::Int("1".into())]),
                Value::List(vec![Value::Str("x".into())]),
                Value::None,
            ]
        );
        assert_eq!(kwargs, vec![("andword", Value::Str(String::new()))]);
        assert_eq!(parse("f(cat)"), None);
        assert_eq!(parse("f('cat'))"), None);
    }

    #[test]
    fn reprs_like_python() {
        let tuple = Value::Tuple(vec![Value::Str("a".into()), Value::Str("b".into())]);
        assert_eq!(tuple.str(), "('a', 'b')");
        assert_eq!(Value::Str("it's".into()).repr(), "\"it's\"");
        assert!(!Value::Int("0".into()).truthy());
        assert!(Value::Int("3".into()).truthy());
        assert!(!Value::Str(String::new()).truthy());
    }
}