Skip to main content

inflect_rs/
inflect_call.rs

1use std::sync::LazyLock;
2
3use fancy_regex::Regex;
4
5use crate::text::{group, regex};
6use crate::{Count, Engine, Error, Gender, NumberToWordsOptions};
7
8static FUNCTION_CALL: LazyLock<Regex> = LazyLock::new(|| regex(r"((\w+)\([^)]*\)*)"));
9
10const METHODS: &[(&str, &[&str])] = &[
11    ("plural", &["text", "count"]),
12    ("plural_adj", &["text", "count"]),
13    ("plural_noun", &["text", "count"]),
14    ("plural_verb", &["text", "count"]),
15    ("singular_noun", &["text", "count", "gender"]),
16    ("a", &["text", "count"]),
17    ("an", &["text", "count"]),
18    ("no", &["text", "count"]),
19    ("ordinal", &["num"]),
20    (
21        "number_to_words",
22        &[
23            "num",
24            "wantlist",
25            "group",
26            "comma",
27            "andword",
28            "zero",
29            "one",
30            "decimal",
31            "threshold",
32        ],
33    ),
34    ("present_participle", &["word"]),
35    ("num", &["count", "show"]),
36];
37
38#[derive(Clone, Debug, PartialEq)]
39enum Value {
40    Str(String),
41    Int(String),
42    Float(String),
43    Bool(bool),
44    None,
45    Tuple(Vec<Value>),
46    List(Vec<Value>),
47}
48
49impl Value {
50    fn repr(&self) -> String {
51        match self {
52            Value::Str(s) if s.contains('\'') && !s.contains('"') => {
53                format!("\"{}\"", s.replace('\\', "\\\\"))
54            }
55            Value::Str(s) => format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'")),
56            Value::Tuple(items) if items.len() == 1 => format!("({},)", items[0].repr()),
57            Value::Tuple(items) => format!("({})", join_reprs(items)),
58            Value::List(items) => format!("[{}]", join_reprs(items)),
59            other => other.str(),
60        }
61    }
62
63    fn str(&self) -> String {
64        match self {
65            Value::Str(s) | Value::Int(s) | Value::Float(s) => s.clone(),
66            Value::Bool(true) => "True".to_string(),
67            Value::Bool(false) => "False".to_string(),
68            Value::None => "None".to_string(),
69            other => other.repr(),
70        }
71    }
72
73    fn truthy(&self) -> bool {
74        match self {
75            Value::Str(s) => !s.is_empty(),
76            Value::Int(s) | Value::Float(s) => s.chars().any(|c| ('1'..='9').contains(&c)),
77            Value::Bool(b) => *b,
78            Value::None => false,
79            Value::Tuple(items) | Value::List(items) => !items.is_empty(),
80        }
81    }
82}
83
84fn join_reprs(items: &[Value]) -> String {
85    items.iter().map(Value::repr).collect::<Vec<_>>().join(", ")
86}
87
88type Call<'a> = (Vec<Value>, Vec<(&'a str, Value)>);
89
90struct Parser<'a> {
91    src: &'a str,
92    pos: usize,
93}
94
95impl<'a> Parser<'a> {
96    fn peek(&self) -> Option<char> {
97        self.src[self.pos..].chars().next()
98    }
99
100    fn bump(&mut self) -> Option<char> {
101        let c = self.peek()?;
102        self.pos += c.len_utf8();
103        Some(c)
104    }
105
106    fn skip_ws(&mut self) {
107        while self.peek().is_some_and(char::is_whitespace) {
108            self.bump();
109        }
110    }
111
112    fn eat(&mut self, c: char) -> bool {
113        self.skip_ws();
114        if self.peek() == Some(c) {
115            self.bump();
116            true
117        } else {
118            false
119        }
120    }
121
122    fn ident(&mut self) -> &'a str {
123        let start = self.pos;
124        while self.peek().is_some_and(|c| c.is_alphanumeric() || c == '_') {
125            self.bump();
126        }
127        &self.src[start..self.pos]
128    }
129
130    fn string(&mut self, quote: char) -> Option<Value> {
131        let mut s = String::new();
132        loop {
133            match self.bump()? {
134                c if c == quote => return Some(Value::Str(s)),
135                '\\' => match self.bump()? {
136                    'n' => s.push('\n'),
137                    't' => s.push('\t'),
138                    c @ ('\\' | '\'' | '"') => s.push(c),
139                    c => {
140                        s.push('\\');
141                        s.push(c);
142                    }
143                },
144                c => s.push(c),
145            }
146        }
147    }
148
149    fn number(&mut self) -> Option<Value> {
150        let start = self.pos;
151        if self.peek() == Some('-') {
152            self.bump();
153        }
154        while self
155            .peek()
156            .is_some_and(|c| c.is_ascii_digit() || c == '_' || c == '.')
157        {
158            self.bump();
159        }
160        let text = self.src[start..self.pos].replace('_', "");
161        if text.is_empty() || text == "-" {
162            return None;
163        }
164        Some(if text.contains('.') {
165            Value::Float(text)
166        } else {
167            let negative = text.starts_with('-');
168            let digits = text.trim_start_matches('-').trim_start_matches('0');
169            let digits = if digits.is_empty() { "0" } else { digits };
170            Value::Int(format!(
171                "{}{digits}",
172                if negative && digits != "0" { "-" } else { "" }
173            ))
174        })
175    }
176
177    fn sequence(&mut self, close: char) -> Option<(Vec<Value>, bool)> {
178        let mut items = Vec::new();
179        let mut trailing_comma = false;
180        loop {
181            if self.eat(close) {
182                return Some((items, trailing_comma));
183            }
184            items.push(self.value()?);
185            trailing_comma = self.eat(',');
186            if !trailing_comma {
187                return self.eat(close).then_some((items, false));
188            }
189        }
190    }
191
192    fn value(&mut self) -> Option<Value> {
193        self.skip_ws();
194        match self.peek()? {
195            q @ ('\'' | '"') => {
196                self.bump();
197                self.string(q)
198            }
199            '(' => {
200                self.bump();
201                let (mut items, trailing_comma) = self.sequence(')')?;
202                Some(if items.len() == 1 && !trailing_comma {
203                    items.remove(0)
204                } else {
205                    Value::Tuple(items)
206                })
207            }
208            '[' => {
209                self.bump();
210                Some(Value::List(self.sequence(']')?.0))
211            }
212            c if c.is_ascii_digit() || c == '-' || c == '.' => self.number(),
213            _ => match self.ident() {
214                "True" => Some(Value::Bool(true)),
215                "False" => Some(Value::Bool(false)),
216                "None" => Some(Value::None),
217                _ => None,
218            },
219        }
220    }
221
222    fn call(&mut self) -> Option<Call<'a>> {
223        self.ident();
224        if !self.eat('(') {
225            return None;
226        }
227        let mut args = Vec::new();
228        let mut kwargs = Vec::new();
229        loop {
230            if self.eat(')') {
231                break;
232            }
233            self.skip_ws();
234            let checkpoint = self.pos;
235            let name = self.ident();
236            if !name.is_empty() && self.eat('=') {
237                kwargs.push((name, self.value()?));
238            } else {
239                self.pos = checkpoint;
240                if !kwargs.is_empty() {
241                    return None;
242                }
243                args.push(self.value()?);
244            }
245            if !self.eat(',') {
246                if !self.eat(')') {
247                    return None;
248                }
249                break;
250            }
251        }
252        self.skip_ws();
253        (self.pos == self.src.len()).then_some((args, kwargs))
254    }
255}
256
257fn bind(
258    params: &[&str],
259    args: Vec<Value>,
260    kwargs: Vec<(&str, Value)>,
261) -> Option<Vec<Option<Value>>> {
262    if args.len() > params.len() {
263        return None;
264    }
265    let mut bound: Vec<Option<Value>> = vec![None; params.len()];
266    for (slot, arg) in bound.iter_mut().zip(args) {
267        *slot = Some(arg);
268    }
269    for (name, value) in kwargs {
270        let index = params.iter().position(|p| *p == name)?;
271        if bound[index].replace(value).is_some() {
272            return None;
273        }
274    }
275    Some(bound)
276}
277
278impl Engine {
279    /// Performs the inflections written as function calls inside `text`.
280    ///
281    /// `"The plural of cat is plural('cat')"` becomes
282    /// `"The plural of cat is cats"`. The available functions are `plural`,
283    /// `plural_noun`, `plural_verb`, `plural_adj`, `singular_noun`, `a`, `an`,
284    /// `no`, `ordinal`, `number_to_words`, `present_participle` and `num`,
285    /// taking the same arguments as the Python library.
286    pub fn inflect(&mut self, text: &str) -> Result<String, Error> {
287        let saved_count = self.persistent_count();
288        let result = self.substitute_calls(text);
289        self.num(saved_count);
290        result
291    }
292
293    fn substitute_calls(&mut self, text: &str) -> Result<String, Error> {
294        let mut out = String::with_capacity(text.len());
295        let mut last = 0;
296        for caps in FUNCTION_CALL.captures_iter(text) {
297            let Ok(caps) = caps else { break };
298            let whole = caps.get(0).expect("group 0 always matches");
299            out.push_str(&text[last..whole.start()]);
300            out.push_str(&self.substitute(group(&caps, 1), group(&caps, 2))?);
301            last = whole.end();
302        }
303        out.push_str(&text[last..]);
304        Ok(out)
305    }
306
307    fn substitute(&mut self, call: &str, name: &str) -> Result<String, Error> {
308        let Some(&(_, params)) = METHODS.iter().find(|(method, _)| *method == name) else {
309            return Ok(call.to_string());
310        };
311        let bad_call = || Error::BadInflectCall(call.to_string());
312        let mut parser = Parser { src: call, pos: 0 };
313        let (args, kwargs) = parser.call().ok_or_else(bad_call)?;
314        let mut bound = bind(params, args, kwargs).ok_or_else(bad_call)?.into_iter();
315        let mut next = || bound.next().flatten();
316
317        let text = |value: Option<Value>| match value {
318            Some(Value::Str(s)) if !s.is_empty() => Ok(s),
319            _ => Err(bad_call()),
320        };
321        let count = |value: Option<Value>| match value {
322            None | Some(Value::None) => None,
323            Some(Value::Int(n)) => Some(n.parse().map_or(Count::Word(n), Count::Num)),
324            Some(other) => Some(Count::Word(other.str())),
325        };
326
327        Ok(match name {
328            "plural" | "plural_adj" | "plural_noun" | "plural_verb" => {
329                let (word, count) = (text(next())?, count(next()));
330                let count = count.as_ref();
331                match name {
332                    "plural" => self.plural_count(&word, count),
333                    "plural_adj" => self.plural_adj_count(&word, count),
334                    "plural_noun" => self.plural_noun_count(&word, count),
335                    _ => self.plural_verb_count(&word, count),
336                }
337            }
338            "singular_noun" => {
339                let (word, count) = (text(next())?, count(next()));
340                let gender = match next() {
341                    None | Some(Value::None) => None,
342                    Some(Value::Str(g)) => Some(g.parse::<Gender>()?),
343                    Some(_) => return Err(bad_call()),
344                };
345                self.singular_noun_count(&word, count.as_ref(), gender)
346                    .ok_or_else(bad_call)?
347            }
348            "a" | "an" => {
349                let word = text(next())?;
350                let count = match next() {
351                    None => Count::Num(1),
352                    Some(value) => count(Some(value)).unwrap_or(Count::Word("None".into())),
353                };
354                self.a_with_count(&word, count)
355            }
356            "no" => {
357                let word = text(next())?;
358                match count(next()) {
359                    Some(count) => self.no_with_count(&word, count),
360                    None => self.no(&word),
361                }
362            }
363            "ordinal" => match next() {
364                Some(Value::Str(s)) if !s.is_empty() => self.ordinal(s),
365                Some(n @ (Value::Int(_) | Value::Float(_))) => self.ordinal(n.str()),
366                _ => return Err(bad_call()),
367            },
368            "number_to_words" => {
369                let num = match next() {
370                    Some(Value::Str(s)) if !s.is_empty() => s,
371                    Some(n @ (Value::Int(_) | Value::Float(_))) => n.str(),
372                    _ => return Err(bad_call()),
373                };
374                if next().is_some_and(|wantlist| wantlist.truthy()) {
375                    return Err(bad_call());
376                }
377                let defaults = NumberToWordsOptions::default();
378                let string_or = |value: Option<Value>, default: String| match value {
379                    None => Ok(default),
380                    Some(Value::Str(s)) => Ok(s),
381                    Some(_) => Err(bad_call()),
382                };
383                let options = NumberToWordsOptions {
384                    group: match next() {
385                        None => 0,
386                        Some(Value::Int(n)) => n.parse().map_err(|_| Error::BadChunkingOption)?,
387                        Some(_) => return Err(bad_call()),
388                    },
389                    comma: match next() {
390                        None => defaults.comma,
391                        Some(Value::Str(s)) => s,
392                        Some(Value::Bool(false) | Value::None) => String::new(),
393                        Some(_) => return Err(bad_call()),
394                    },
395                    andword: string_or(next(), defaults.andword)?,
396                    zero: string_or(next(), defaults.zero)?,
397                    one: string_or(next(), defaults.one)?,
398                    decimal: match next() {
399                        None => defaults.decimal,
400                        Some(Value::Str(s)) => Some(s),
401                        Some(Value::Bool(false) | Value::None) => None,
402                        Some(_) => return Err(bad_call()),
403                    },
404                    threshold: match next() {
405                        None | Some(Value::None) => None,
406                        Some(Value::Int(n)) => Some(n.parse().map_err(|_| bad_call())?),
407                        Some(_) => return Err(bad_call()),
408                    },
409                };
410                self.number_to_words_with(num, &options)?
411            }
412            "present_participle" => self.present_participle(&text(next())?),
413            "num" => {
414                let value = next();
415                let show = next();
416                let count = match &value {
417                    None | Some(Value::None) => None,
418                    Some(Value::Bool(b)) => Some(i64::from(*b)),
419                    Some(Value::Float(f)) => Some(
420                        f.parse::<f64>()
421                            .map_err(|_| Error::BadNumValue(f.clone()))?
422                            .trunc() as i64,
423                    ),
424                    Some(other) => {
425                        let s = other.str();
426                        Some(s.trim().parse().map_err(|_| Error::BadNumValue(s))?)
427                    }
428                };
429                self.num(count);
430                match (&value, show) {
431                    (None | Some(Value::None), _) => String::new(),
432                    (_, Some(show)) if show != Value::None && !show.truthy() => String::new(),
433                    (Some(value), _) => value.str(),
434                }
435            }
436            _ => unreachable!("method table and dispatch agree"),
437        })
438    }
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444
445    fn parse(call: &str) -> Option<Call<'_>> {
446        Parser { src: call, pos: 0 }.call()
447    }
448
449    #[test]
450    fn parses_literals() {
451        let (args, kwargs) = parse("f('a', 2, (1,), ['x'], None, andword='')").unwrap();
452        assert_eq!(
453            args,
454            vec![
455                Value::Str("a".into()),
456                Value::Int("2".into()),
457                Value::Tuple(vec![Value::Int("1".into())]),
458                Value::List(vec![Value::Str("x".into())]),
459                Value::None,
460            ]
461        );
462        assert_eq!(kwargs, vec![("andword", Value::Str(String::new()))]);
463        assert_eq!(parse("f(cat)"), None);
464        assert_eq!(parse("f('cat'))"), None);
465    }
466
467    #[test]
468    fn reprs_like_python() {
469        let tuple = Value::Tuple(vec![Value::Str("a".into()), Value::Str("b".into())]);
470        assert_eq!(tuple.str(), "('a', 'b')");
471        assert_eq!(Value::Str("it's".into()).repr(), "\"it's\"");
472        assert!(!Value::Int("0".into()).truthy());
473        assert!(Value::Int("3".into()).truthy());
474        assert!(!Value::Str(String::new()).truthy());
475    }
476}