nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use super::money;
use crate::{Context, Error, Outcome, Plugin, number, re};
use chrono::Datelike;
pub struct Finance;
fn words(s: &str) -> String {
    let mut s = s.to_lowercase();
    for (w, n) in [
        ("one", "1"),
        ("two", "2"),
        ("three", "3"),
        ("four", "4"),
        ("five", "5"),
        ("six", "6"),
        ("seven", "7"),
        ("eight", "8"),
        ("nine", "9"),
        ("ten", "10"),
    ] {
        s = s
            .split_whitespace()
            .map(|t| if t == w { n } else { t })
            .collect::<Vec<_>>()
            .join(" ");
    }
    s
}
pub(super) fn currency(s: &str) -> Option<&'static str> {
    match s.trim().to_lowercase().as_str() {
        "aud" | "australian dollars" | "dollars" | "dollar" | "$" | "dollars aud" => Some("AUD"),
        "usd" | "us dollars" | "us$" => Some("USD"),
        "eur" | "euro" | "euros" | "€" => Some("EUR"),
        "gbp" | "pounds" | "£" => Some("GBP"),
        "jpy" | "yen" | "¥" => Some("JPY"),
        "btc" | "₿" => Some("BTC"),
        _ => None,
    }
}
/// Validate an explicitly supplied common-base FX binding against the context.
pub(super) fn validate_supplied_rate(
    currency_name: &str,
    input: &str,
    engine: &super::compositions::Compositions,
    context: &Context,
) -> Result<(), Error> {
    let code = currency(currency_name).ok_or_else(|| Error("incompatible_units".into()))?;
    let value = engine.quantity_value(input, "1", context)?;
    let expected = context
        .rates
        .get(code)
        .filter(|rate| rate.is_finite() && **rate > 0.0)
        .ok_or_else(|| Error("invalid_financial_rate".into()))?;
    if value <= 0.0
        || engine.quantity_order(input, &expected.to_string(), context)?
            != std::cmp::Ordering::Equal
    {
        return Err(Error("invalid_financial_rate".into()));
    }
    Ok(())
}
pub(crate) fn amount(s: &str) -> Option<(f64, &'static str)> {
    let s = s.trim();
    if let Some(code) = currency(s) {
        return Some((1.0, code));
    }
    let c = re!(r"(?i)^([^\d+-.]*)([+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?)(.*)$")
        .captures(s)?;
    let n = c[2].replace(',', "").parse::<f64>().ok()?;
    let before = c[1].trim();
    let after = c[3].trim();
    if !before.is_empty() && currency(before).is_none() {
        return None;
    }
    let code = if !after.is_empty() {
        currency(after)?
    } else if !before.is_empty() {
        currency(before)?
    } else {
        ""
    };
    Some((n, code))
}
fn years(n: f64, unit: &str) -> Option<f64> {
    Some(match unit {
        "year" | "years" => n,
        "month" | "months" => n / 12.0,
        "week" | "weeks" => n / 52.1775,
        "day" | "days" => n / 365.2425,
        "hour" | "hours" => n / 8765.82,
        _ => return None,
    })
}
pub(crate) fn compound_balance(
    principal: f64,
    annual_rate: f64,
    years: f64,
    frequency: f64,
) -> f64 {
    principal * (1.0 + annual_rate / frequency).powf(years * frequency)
}
pub(crate) fn render(n: f64, code: &str) -> Outcome {
    if !n.is_finite() {
        None
    } else {
        Some(Ok(if code.is_empty() {
            number(n)
        } else {
            money(n, code)
        }))
    }
}
impl Plugin for Finance {
    fn evaluate(&self, input: &str, ctx: &Context) -> Outcome {
        let s = words(input).replace("percent", "%");
        if s.contains(" into ")
            && !s.starts_with("convert ")
            && re!(r"US\$|[$€£¥₿]|\b(?:aud|usd|eur|gbp|jpy|btc|dollars?|euros?|yen)\b").is_match(&s)
        {
            return Some(Err(Error("invalid_expression".into())));
        }
        // Keep a computed monetary source typed when the converter belongs to
        // physical units. Letting Units consume it would turn its currency into
        // a comment and attach the money coordinate to the requested unit.
        if let Some((source, target)) = super::syntax::split_last(&s, super::syntax::CONVERSIONS)
            && currency(target).is_none()
            && super::units::Units::default().unit(target).is_some()
            && expression(source, ctx, 0).is_some_and(|(_, code)| !code.is_empty())
            // Currency words can also name physical units, e.g. pounds of mass.
            && !super::units::Units::default().expression(source, 0).is_ok_and(|q| {
                q.unit.dimension != [0; 8]
                    && super::units::Units::default().unit(target)
                        .is_some_and(|unit| unit.dimension == q.unit.dimension)
            })
        {
            return Some(Err(Error("internal_error".into())));
        }
        if let Some(lowered) = super::compositions::standard_grouped_comments(&s) {
            if let Some(result) = super::calendar::Calendar.evaluate(&s, ctx) {
                return Some(result);
            }
            return match lowered {
                Ok(lowered) => self
                    .evaluate(&lowered, ctx)
                    .or_else(|| super::arithmetic::eval(&lowered).map(|value| Ok(number(value)))),
                Err(error) => Some(Err(error)),
            };
        }
        if let Some(c) = re!(r"^(.+) per (\w+) for (.+) in (.+)$").captures(&s) {
            let (n, code) = amount(&c[1])?;
            let target = currency(&c[4])?;
            let units = super::units::Units::default();
            let duration = units.quantity(&c[3])?;
            let period = units.unit(&c[2])?;
            if duration.unit.dimension != [0, 0, 1, 0, 0, 0, 0, 0]
                || period.dimension != duration.unit.dimension
                || code != target
            {
                return None;
            }
            return render(n * duration.base / period.scale, code);
        }
        if let Some(c) =
            re!(r"^(.+) per (\w+) (?:as|in) (.+?) per (\w+)(?: at ([\d.]+) hours per (\w+))?$")
                .captures(&s)
        {
            let (n, code) = amount(&c[1])?;
            let target = currency(&c[3])?;
            if code != target {
                return None;
            }
            let units = super::units::Units::default();
            let from = units.unit(&c[2])?;
            let to = units.unit(&c[4])?;
            if from.dimension != [0, 0, 1, 0, 0, 0, 0, 0] || to.dimension != from.dimension {
                return None;
            }
            let n = n * to.scale / from.scale;
            let (n, label) = if let Some(hours) = c.get(5) {
                (n * hours.as_str().parse::<f64>().ok()?, c[6].to_string())
            } else {
                (n, c[4].to_string())
            };
            return Some(Ok(format!("{}/{}", money(n, code), label)));
        }

        if let Some(c) = re!(
            r"^present value of (.+) (?:after|over) ([\d.]+) (years?|months?) at ([+-]?[\d.]+)%$"
        )
        .captures(&s)
        {
            let (p, code) = amount(&c[1])?;
            return render(
                p / (1.0 + c[4].parse::<f64>().ok()? / 100.0)
                    .powf(years(c[2].parse().ok()?, &c[3])?),
                code,
            );
        }
        if let Some(c)=re!(r"^(?:annual return on )?(.+) invested (.+) returned(?: (?:after|over) ([\d.]+) (years?|months?))?$").captures(&s){let(a,_)=amount(&c[1])?;let(b,_)=amount(&c[2])?;return if let Some(t)=c.get(3){Some(Ok(format!("{}%",number(((b/a).powf(1.0/years(t.as_str().parse().ok()?,&c[4])?)-1.0)*100.0))))}else{Some(Ok(format!("{}x",number(b/a-1.0))))};}
        if let Some(c) =
            re!(r"^investment required for (.+) per (month|year) at ([+-]?[\d.]+)%$").captures(&s)
        {
            let (value, code) = amount(&c[1])?;
            if c[3].parse::<f64>().ok()? == 0.0 {
                return Some(Ok("Error: ∞".into()));
            }
            return render(
                value / years(1.0, &c[2])? / (c[3].parse::<f64>().ok()? / 100.0),
                code,
            );
        }
        if let Some(c) = re!(r"^(.+) per (.+) is what per (.+)$").captures(&s) {
            let (value, code) = amount(&c[1])?;
            if code.is_empty() {
                return None;
            }
            let units = super::units::Units::default();
            let a = units.unit(&c[2])?;
            let b = units.unit(&c[3])?;
            if a.dimension != b.dimension {
                return None;
            }
            return Some(Ok(format!(
                "{}/{}",
                money(value * b.scale / a.scale, code),
                b.symbol
            )));
        }
        let loan = re!(
            r"^(total|monthly|weekly|annual|quarterly) (interest (?:repayment )?|repayment )on (.+)$"
        );
        if let Some(c) = loan.captures(&s) {
            let raw = &c[3];
            let is_interest = c[2].starts_with("interest");
            let compound = is_interest
                && !c[2].contains("repayment")
                && &c[1] != "total"
                && (raw.contains("compounding") || raw.find(" at ") < raw.find(" for "));
            if !compound {
                let parameters=re!(r"^(?:(.+) (?:for|over) ([\d.]+) (years?|months?) at ([+-]?[\d.]+)%|(.+) at ([+-]?[\d.]+)% (?:for|over) ([\d.]+) (years?|months?))$").captures(raw)?;
                let (p, code, t, r) = if parameters.get(1).is_some() {
                    let (p, code) = amount(&parameters[1])?;
                    (
                        p,
                        code,
                        years(parameters[2].parse().ok()?, &parameters[3])?,
                        parameters[4].parse::<f64>().ok()? / 1200.0,
                    )
                } else {
                    let (p, code) = amount(&parameters[5])?;
                    (
                        p,
                        code,
                        years(parameters[7].parse().ok()?, &parameters[8])?,
                        parameters[6].parse::<f64>().ok()? / 1200.0,
                    )
                };
                if r == 0.0 || t == 0.0 {
                    return Some(Err(Error("internal_error".into())));
                }
                let months = t * 12.0;
                let payment = if r == 0.0 {
                    p / months
                } else {
                    p * r / (1.0 - (1.0 + r).powf(-months))
                };
                let total = payment * months - if is_interest { p } else { 0.0 };
                let frequency = match &c[1] {
                    "monthly" => 12.0,
                    "weekly" => 52.1775,
                    "quarterly" => 4.0,
                    _ => 1.0,
                };
                return render(
                    if &c[1] == "total" {
                        total
                    } else {
                        total / t / frequency
                    },
                    code,
                );
            }
        }
        if let Some(c)=re!(r"^(?:value of |purchasing power of |what will )(.+?)(?: be worth)? in (\d{4}) (?:assuming|at|with|given) ([+-]?[\d.]+)% inflation$").captures(&s){if c[3].starts_with("-0."){return None;}let(p,code)=amount(&c[1])?;let years=c[2].parse::<i32>().ok()?-ctx.now.with_timezone(&ctx.timezone).year();return render(p/(1.0+c[3].parse::<f64>().ok()?/100.0).powi(years),code);}
        let pattern = re!(
            r"^monthly repayment on (.+) (?:over|for) ([\d.]+) (years?|months?) at ([+-]?[\d.]+)\s*%$"
        );
        if let Some(c) = pattern.captures(&s) {
            let (principal, code) = amount(&c[1])?;
            let periods = years(c[2].parse().ok()?, &c[3])? * 12.0;
            let rate = c[4].parse::<f64>().ok()? / 1200.0;
            return render(principal * rate / (1.0 - (1.0 + rate).powf(-periods)), code);
        }
        let interest =
            re!(r"^(?:(monthly|quarterly|annual|weekly) )?interest on (.+)$").captures(&s);
        let comp_input = interest
            .as_ref()
            .map(|c| c.get(2).unwrap().as_str())
            .unwrap_or(&s);
        if let Some((mut result, code, principal)) = standard_compound(comp_input) {
            if let Some(interest) = interest {
                result -= principal;
                result /= match interest.get(1).map(|m| m.as_str()) {
                    Some("monthly") => 12.0,
                    Some("quarterly") => 4.0,
                    Some("weekly") => 52.1775,
                    _ => 1.0,
                };
            }
            return render(result, code);
        }
        let pattern = re!(
            r"^([+-]?[\d.]+) hours? at (.+?)(?:/hour| per hour)(?: for ([+-]?[\d.]+) weeks?)?(?: in (.+))?$"
        );
        if let Some(c) = pattern.captures(&s) {
            let hours = c[1].parse::<f64>().ok()?;
            let (rate, code) = amount(&c[2])?;
            let mut value = hours
                * rate
                * c.get(3)
                    .map(|m| m.as_str().parse::<f64>().ok())
                    .unwrap_or(Some(1.0))?;
            let mut target = code;
            if let Some(to) = c.get(4) {
                target = currency(to.as_str())?;
                value *= ctx.rates.get(target)? / ctx.rates.get(code)?;
            }
            return render(value, target);
        }
        if amount(&s).is_none()
            && let Some((value, code)) = expression(&s, ctx, 0)
            && (!code.is_empty()
                || re!(r"(?i)US\$|[$€£¥₿]|\b(?:AUD|USD|EUR|GBP|JPY|BTC|dollars?|euros?|yen)\b")
                    .is_match(&s))
        {
            return if value.is_finite() {
                render(value, code)
            } else {
                Some(Err(Error("internal_error".into())))
            };
        }
        let s = if let Some(rest) = s.strip_prefix("convert ") {
            if !rest.contains(" into ") {
                return None;
            }
            rest
        } else {
            s.as_str()
        };
        let parts: Vec<_> = re!(r" (?:to|in|into|as) ").split(s).collect();
        if parts.len() < 2 {
            return None;
        }
        if let Some(c) = re!(r"^([+-]?[\d.]+)% ([a-z]+)$").captures(parts[0]) {
            currency(&c[2])?;
            currency(parts[1])?;
            return Some(Ok(format!("{}%", number(c[1].parse().ok()?))));
        }
        let (mut value, mut code) = amount(parts[0])?;
        for target in &parts[1..] {
            if let Some((n, to)) = amount(target).filter(|(_, c)| !c.is_empty())
                && currency(target).is_none()
            {
                value = n - value * ctx.rates.get(to)? / ctx.rates.get(code)?;
                code = to;
                continue;
            }
            let target = currency(target)?;
            if code.is_empty() {
                code = target;
            } else if code != target {
                value *= ctx.rates.get(target)? / ctx.rates.get(code)?;
                code = target;
            }
        }
        render(value, code)
    }
}

pub(crate) fn expression(input: &str, ctx: &Context, depth: usize) -> Option<(f64, &'static str)> {
    if depth > 64 {
        return None;
    }
    let normalized = input
        .replace(" plus ", " + ")
        .replace(" minus ", " - ")
        .replace(" divided by ", " / ")
        .replace(" multiplied by ", " * ");
    let s = normalized.trim();
    let operators = super::arithmetic::operators(s)?;
    if let Some((left, right)) = s.rsplit_once(" times ") {
        return Some((
            expression(left, ctx, depth + 1)?.0 * expression(right, ctx, depth + 1)?.0,
            "",
        ));
    }
    let convert = |n: f64, from: &str, to: &str| -> Option<f64> {
        if from.is_empty() || from == to {
            Some(n)
        } else {
            Some(n / ctx.rates.get(from)? * ctx.rates.get(to)?)
        }
    };
    for separator in [" to ", " in ", " into ", " as "] {
        if let Some((left, right)) = s.rsplit_once(separator)
            && let Some(target) = currency(right)
        {
            let (n, code) = expression(left, ctx, depth + 1)?;
            return Some((convert(n, code, target)?, target));
        }
    }
    for level in ["+-", "*/"] {
        if let Some(&(i, op)) = operators.iter().rev().find(|(_, op)| level.contains(*op)) {
            let (a, ac) = expression(&s[..i], ctx, depth + 1)?;
            let (b, bc) = expression(&s[i + 1..], ctx, depth + 1)?;
            if matches!(op, '+' | '-') && s[i + 1..].trim().ends_with('%') {
                return Some((a * (1.0 + if op == '+' { b } else { -b }), ac));
            }
            let code = if (op == '-' && !ac.is_empty()) || bc.is_empty() {
                ac
            } else {
                bc
            };
            return Some(match op {
                '+' => (convert(a, ac, code)? + convert(b, bc, code)?, code),
                '-' => (convert(a, ac, code)? - convert(b, bc, code)?, code),
                '*' => (a * b, code),
                '/' if !ac.is_empty() && !bc.is_empty() => (convert(a, ac, bc)? / b, ""),
                '/' => (a / b, code),
                _ => unreachable!(),
            });
        }
    }
    if let Some(inner) = s.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
        return expression(inner, ctx, depth + 1);
    }
    if let Some(rest) = s.strip_prefix('-') {
        let (n, code) = expression(rest, ctx, depth + 1)?;
        return Some((-n, code));
    }
    if let Some(c) = re!(r"^([+-]?[\d.]+)% (of|on|off) (.+)$").captures(s) {
        let p = c[1].parse::<f64>().ok()?;
        let (n, code) = expression(&c[3], ctx, depth + 1)?;
        return Some((percentage_amount(n, p, &c[2]), code));
    }
    amount(s)
        .or_else(|| Some((s.strip_suffix('%')?.trim().parse::<f64>().ok()? / 100.0, "")))
        .or_else(|| super::arithmetic::eval(s).map(|n| (n, "")))
}

fn percentage_amount(amount: f64, percentage: f64, operation: &str) -> f64 {
    let p = percentage / 100.0;
    amount
        * match operation {
            "on" => 1.0 + p,
            "off" => 1.0 - p,
            _ => p,
        }
}

/// A contiguous percentage word function remains active inside standard prose.
/// Intervening comments, e.g. `% margin on`, do not form that word function.
pub(crate) fn standard_percentage_span(input: &str) -> Option<(f64, &'static str)> {
    let c = re!(r"(?i)([+-]?[\d.]+)%\s+(of|on|off)\s+((?:us\$|[$€£¥₿])\s*[+-]?[\d,]+(?:\.\d+)?|[+-]?[\d,]+(?:\.\d+)?\s+(?:aud|usd|eur|gbp|jpy|btc|dollars?|euros?|pounds?|yen))").captures(input)?;
    // A complete expression keeps its existing evaluator and precision policy.
    if c.get(0)?.as_str() == input.trim() {
        return None;
    }
    let (amount, code) = amount(&c[3])?;
    Some((
        percentage_amount(amount, c[1].parse().ok()?, &c[2].to_lowercase()),
        code,
    ))
}

/// Standard compound word functions retain the original operation order.
pub(crate) fn standard_compound(input: &str) -> Option<(f64, &'static str, f64)> {
    let comp = re!(
        r"^(?:([\w$€£¥₿.,+\- ]+) at ([+-]?[\d.]+)\s*% (?:for|over) ([+-]?[\d.]+) (years?|months?|weeks?|days?|hours?)|([\w$€£¥₿.,+\- ]+) (?:over|for|after) ([+-]?[\d.]+) (years?|months?|weeks?|days?|hours?) at ([+-]?[\d.]+)\s*%)(?: compound(?:ed|ing) (yearly|monthly|quarterly|weekly|daily|hourly))?$"
    );
    let c = comp.captures(input)?;
    let (a, rate, n, unit) = if c.get(1).is_some() {
        (&c[1], &c[2], &c[3], &c[4])
    } else {
        (&c[5], &c[8], &c[6], &c[7])
    };
    let (principal, code) = amount(a)?;
    let r = rate.parse::<f64>().ok()? / 100.0;
    let t = years(n.parse().ok()?, unit)?;
    let frequency = match c.get(9).map(|m| m.as_str()) {
        Some("monthly") => 12.0,
        Some("quarterly") => 4.0,
        Some("weekly") => 52.1775,
        Some("daily") => 365.2425,
        Some("hourly") => 8765.82,
        _ => 1.0,
    };
    let result = compound_balance(principal, r, t, frequency);
    Some((result, code, principal))
}

/// Find an atomic standard money/rate/duration word function inside a comment group.
pub(crate) fn standard_compound_span(input: &str) -> Option<(f64, &'static str)> {
    let span = re!(r"(?i)(?:(?:us\$|[$€£¥₿])\s*[+-]?[\d,]+(?:\.\d+)?|[+-]?[\d,]+(?:\.\d+)?\s+(?:aud|usd|eur|gbp|jpy|btc|dollars?|euros?|pounds?|yen))\s+(?:at\s+[+-]?[\d.]+\s*%\s+(?:for|over)\s+[+-]?[\d.]+\s+(?:years?|months?|weeks?|days?|hours?)|(?:after|over|for)\s+[+-]?[\d.]+\s+(?:years?|months?|weeks?|days?|hours?)\s+at\s+[+-]?[\d.]+\s*%)(?:\s+compound(?:ed|ing)\s+(?:yearly|monthly|quarterly|weekly|daily|hourly))?").find(input)?;
    standard_compound(span.as_str()).map(|(value, code, _)| (value, code))
}