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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! Complete supplied business roles lower to ordinary typed money expressions.
use super::{compositions::Compositions, syntax};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};
use std::cmp::Ordering;

mod balances;
mod inventory;
mod prices;

/// The Finance story recognizer must leave only this complete included-tax
/// installment sentence family to the Business owner.
pub(super) fn included_installment_request(input: &str) -> bool {
    balances::inclusive_installment_request(input)
}

/// Finance declines only this complete staged-coupon report family.
pub(super) fn staged_coupon_gift_request(input: &str) -> bool {
    prices::staged_coupon_gift_request(input)
}

/// Closed coupon/tax/card report vocabulary. Keep the caller's requested
/// label while using this index to reject omitted and repeated stage goals.
fn coupon_goal_stage(label: &str) -> Option<usize> {
    Some(match label {
        "original amount" | "purchase amount" => 0,
        "coupon value" | "coupon savings" | "discount" | "discount amount" => 1,
        "tax base"
        | "taxable amount"
        | "taxable subtotal"
        | "discounted base"
        | "coupon-adjusted base"
        | "base" => 2,
        "tax" => 3,
        "taxed total" | "post-tax total" | "after-tax bill" | "post-tax amount"
        | "total before card" | "total" => 4,
        "card used" | "gift card applied" | "card redemption" | "card amount used"
        | "card applied" | "credit applied" | "redemption" => 5,
        "remaining due" | "amount due" | "final amount due" | "balance due" | "payable balance"
        | "cash due" | "due" => 6,
        _ => return None,
    })
}

fn included_installment_goal_stage(label: &str) -> Option<usize> {
    Some(match label {
        "base"
        | "pre-tax amount"
        | "net amount"
        | "net"
        | "pre-tax value"
        | "net price"
        | "tax-exclusive price"
        | "pretax value"
        | "taxable base" => 0,
        "tax" | "included tax" | "embedded tax" | "tax component" => 1,
        "remaining balance"
        | "post-deposit balance"
        | "balance after upfront payment"
        | "balance"
        | "installment balance"
        | "remaining sum" => 2,
        "repeated installment"
        | "regular installment"
        | "first installment"
        | "standard installment"
        | "regular share"
        | "ordinary payment" => 3,
        "residual" | "final residual" | "last installment" | "last share" | "final payment"
        | "final one" => 4,
        _ => return None,
    })
}

/// FinanceQueries leaves this complete fee-bearing simple-interest clause to
/// BusinessQueries; keep both owners on the same recognition boundary.
pub(super) fn simple_interest_fee_request(input: &str) -> Option<regex::Captures<'_>> {
    let input = input.trim().trim_end_matches(['?', '.']);
    re!(r"(?i)^a business has (.+?) in its account, earns (.+?)% simple annual interest for (.+?) months, and pays a (.+?) fee; what is the ending balance$").captures(input)
}

/// Finance must leave these complete fee-priority allocation reports to the
/// Business owner, which keeps fee and principal as separate money roles.
pub(super) fn fee_priority_request(input: &str) -> bool {
    let input = syntax::ungroup(input.trim()).trim_end_matches(['?', '.']);
    re!(r"(?i)^an account owes .+?\. apply a .+? late fee first, then a .+? payment; allocate the payment to the fee before principal\. (?:report|give) .+$")
        .is_match(input)
        || re!(r"(?i)^a .+? debt receives a .+? fee before a .+? payment, which is allocated first to fees and then principal\. (?:report|give) .+$")
            .is_match(input)
}

/// Complete priority and excess-credit wording shared by Finance admission
/// and the Business owner. Category values and names remain data for one
/// bounded ledger, rather than separate arithmetic rules per sentence.
pub(super) struct PriorityRequest {
    payment: String,
    categories: String,
    both: bool,
    credit_label: &'static str,
}

pub(super) fn priority_ledger_request(input: &str) -> Option<PriorityRequest> {
    let input = syntax::ungroup(input.trim()).trim_end_matches(['?', '.']);
    let forms = [
        (
            re!(
                r"(?i)^allocate a (.+?) payment to (.+?); apply funds in that priority order and report paid and unpaid amounts for each category, with any excess held as account credit$"
            ),
            true,
            "account credit",
        ),
        (
            re!(
                r"(?i)^split a (.+?) payment among (.+?) in that exact priority order; show how much each receives and retain any remaining payment as a customer credit$"
            ),
            false,
            "customer credit",
        ),
        (
            re!(
                r"(?i)^apply (.+?) to balances in this order: (.+?)\. pay each category fully before the next; report the allocation and treat overpayment as a refundable credit$"
            ),
            false,
            "refundable credit",
        ),
        (
            re!(
                r"(?i)^a (.+?) payment must cover (.+?), in that order; give each paid balance and the excess, which stays on the account as credit$"
            ),
            false,
            "account credit",
        ),
    ];
    forms.into_iter().find_map(|(pattern, both, credit_label)| {
        let captures = pattern.captures(input)?;
        Some(PriorityRequest {
            payment: captures[1].to_owned(),
            categories: captures[2].to_owned(),
            both,
            credit_label,
        })
    })
}

#[derive(Default)]
pub struct BusinessQueries {
    engine: Compositions,
}

impl Plugin for BusinessQueries {
    fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
        self.lower(input, context).transpose()
    }
    fn rewrite(&self, input: &str, context: &Context) -> Outcome {
        syntax::rewrite_groups(input, |part| self.lower(part, context).transpose())
    }

    fn evaluate(&self, input: &str, context: &Context) -> Outcome {
        let input = syntax::ungroup(input);
        if let Some(result) = balances::evaluate_priority(&self.engine, input, context) {
            return Some(result);
        }
        if let Some(result) = balances::evaluate_payment_schedule(&self.engine, input, context) {
            return Some(result);
        }
        if !input.contains("business_summary(") {
            return None;
        }
        Some((|| {
            // A labeled answer is standalone; it is not an arithmetic tuple.
            let inner = input
                .strip_prefix("business_summary(")
                .and_then(|s| s.strip_suffix(')'))
                .ok_or_else(|| Error("invalid_expression".into()))?;
            let fields = inner.split(';').collect::<Vec<_>>();
            let utility_six = fields.len() == 6
                && [
                    "energy charge|",
                    "fixed charge|",
                    "credit|",
                    "taxable base|",
                    "tax|",
                    "total|",
                ]
                .iter()
                .all(|label| {
                    fields
                        .iter()
                        .filter(|field| field.starts_with(*label))
                        .count()
                        == 1
                });
            let coupon_six = fields.len() == 6
                && (1..7).all(|stage| {
                    fields
                        .iter()
                        .filter(|field| {
                            field.split('|').next().and_then(coupon_goal_stage) == Some(stage)
                        })
                        .count()
                        == 1
                });
            let coupon_seven = fields.len() == 7
                && (0..7).all(|stage| {
                    fields
                        .iter()
                        .filter(|field| {
                            field.split('|').next().and_then(coupon_goal_stage) == Some(stage)
                        })
                        .count()
                        == 1
                });
            if !(2..=5).contains(&fields.len()) && !utility_six && !coupon_six && !coupon_seven {
                return Err(Error("invalid_expression".into()));
            }
            let mut output = Vec::new();
            for field in fields {
                let mut parts = field.splitn(3, '|');
                let label = parts.next().unwrap_or_default().trim();
                let kind = parts.next().unwrap_or_default().trim();
                let expression = parts
                    .next()
                    .ok_or_else(|| Error("invalid_expression".into()))?;
                let money_label = matches!(
                    label,
                    "profit"
                        | "net profit"
                        | "cash profit"
                        | "selling price"
                        | "cost"
                        | "profit after fee"
                        | "gross profit"
                        | "total sales"
                        | "total cost"
                        | "pre-tax price"
                        | "tax"
                        | "final amount"
                        | "total reduction"
                        | "final price"
                        | "net sales"
                        | "commission"
                        | "payment"
                        | "remaining principal"
                        | "energy charge"
                        | "total bill"
                        | "subtotal"
                        | "pre-tax amount"
                        | "taxable product amount"
                        | "exempt product amount"
                        | "grand total"
                        | "total"
                        | "original amount"
                        | "discount"
                        | "taxable amount"
                        | "fixed charge"
                        | "credit"
                        | "net due"
                        | "taxable base"
                        | "fee"
                        | "payment allocated to fee"
                        | "payment allocated to principal"
                        | "remaining fee"
                        | "principal paid"
                        | "principal remaining"
                        | "total amount still owed"
                        | "gift card applied"
                        | "cash due"
                        | "coupon value"
                        | "purchase amount"
                        | "coupon savings"
                        | "discount amount"
                        | "tax base"
                        | "taxable subtotal"
                        | "discounted base"
                        | "coupon-adjusted base"
                        | "base"
                        | "taxed total"
                        | "post-tax total"
                        | "after-tax bill"
                        | "post-tax amount"
                        | "total before card"
                        | "card used"
                        | "card applied"
                        | "card redemption"
                        | "card amount used"
                        | "credit applied"
                        | "redemption"
                        | "remaining due"
                        | "amount due"
                        | "final amount due"
                        | "balance due"
                        | "payable balance"
                        | "due"
                        | "net amount"
                        | "net"
                        | "pre-tax value"
                        | "net price"
                        | "tax-exclusive price"
                        | "pretax value"
                        | "included tax"
                        | "embedded tax"
                        | "tax component"
                        | "remaining balance"
                        | "post-deposit balance"
                        | "balance after upfront payment"
                        | "balance"
                        | "installment balance"
                        | "remaining sum"
                        | "repeated installment"
                        | "regular installment"
                        | "first installment"
                        | "standard installment"
                        | "regular share"
                        | "ordinary payment"
                        | "residual"
                        | "final residual"
                        | "last installment"
                        | "last share"
                        | "final payment"
                        | "final one"
                );
                let percent_label = matches!(
                    label,
                    "margin"
                        | "markup"
                        | "net margin"
                        | "margin on sales"
                        | "margin after fees"
                        | "margin before discount"
                        | "margin after discount"
                        | "margin on revenue"
                        | "net change"
                );
                let value = if kind == "m" && money_label {
                    self.engine.evaluate_money(expression, context)?
                } else if kind == "n" && label == "item-line count" {
                    let count = expression
                        .parse::<u16>()
                        .ok()
                        .filter(|count| *count <= 256)
                        .ok_or_else(|| Error("invalid_expression".into()))?;
                    count.to_string()
                } else if kind == "c" && label == "final inventory" {
                    let count = self.count(expression, context)?;
                    self.engine
                        .evaluate(&format!("{count} * 1 units"), context)
                        .ok_or_else(|| Error("invalid_expression".into()))??
                } else if kind == "p" && percent_label {
                    self.engine.quantity_value(expression, "1", context)?;
                    let value = self
                        .engine
                        .evaluate(expression, context)
                        .ok_or_else(|| Error("invalid_expression".into()))??;
                    format!("{value}%")
                } else {
                    return Err(Error("invalid_expression".into()));
                };
                let label = if label == "net change" {
                    "net percentage change"
                } else {
                    label
                };
                output.push(format!("{label}: {value}"));
            }
            Ok(output.join("; "))
        })())
    }
}

fn summary(fields: &[(&str, &str, String)]) -> String {
    format!(
        "business_summary({})",
        fields
            .iter()
            .map(|(label, kind, expression)| { format!("{label}|{kind}|{expression}") })
            .collect::<Vec<_>>()
            .join(";")
    )
}
fn profit(revenue: &str, cost: &str) -> String {
    format!("({revenue} - {cost})")
}
fn ratio_percent(numerator: &str, denominator: &str) -> String {
    format!("({numerator} / {denominator}) * 100")
}

impl BusinessQueries {
    fn money(&self, input: &str, positive: bool, context: &Context) -> Result<String, Error> {
        // Validation discards the display; the original formula keeps all intermediate cents.
        self.engine.evaluate_money(input, context)?;
        let zero = format!("0 * ({input})");
        match self.engine.quantity_order(input, &zero, context)? {
            Ordering::Less => return Err(Error("invalid_financial_argument".into())),
            Ordering::Equal if positive => return Err(Error("division_by_zero".into())),
            _ => {}
        }
        Ok(format!("({input})"))
    }
    fn count(&self, input: &str, context: &Context) -> Result<String, Error> {
        let value = self.engine.quantity_value(input, "1", context)?;
        if value < 0.0 {
            return Err(Error("invalid_financial_argument".into()));
        }
        Ok(format!("({input})"))
    }
    fn rate(
        &self,
        input: &str,
        bounded: bool,
        remaining: bool,
        context: &Context,
    ) -> Result<String, Error> {
        // Authored bounds and complements precede binary64 rounding. The existing
        // rational parser owns scalar grammar; computed real/nonrational rates use
        // the ordinary typed engine's validated binary64 value.
        let value = match super::integer_queries::ratio_value(input) {
            Ok((numerator, denominator)) => {
                let denominator = denominator * 100;
                if numerator.is_negative() || (bounded && numerator > denominator) {
                    return Err(Error("invalid_financial_rate".into()));
                }
                let numerator = if remaining {
                    &denominator - numerator
                } else {
                    numerator
                };
                let nonzero = !numerator.is_zero();
                let value = BigRational::new(numerator, denominator)
                    .to_f64()
                    .ok_or_else(|| Error("numeric_overflow".into()))?;
                if value == 0.0 && nonzero {
                    return Err(Error("numeric_underflow".into()));
                }
                value
            }
            Err(error)
                if matches!(
                    error.0.as_str(),
                    "invalid_integer_expression" | "non_rational_expression"
                ) =>
            {
                let value = self.engine.quantity_value(input, "1", context)?;
                if value < 0.0 || (bounded && value > 100.0) {
                    return Err(Error("invalid_financial_rate".into()));
                }
                let fraction = value / 100.0;
                if fraction == 0.0 && value != 0.0 {
                    return Err(Error("numeric_underflow".into()));
                }
                if remaining { 1.0 - fraction } else { fraction }
            }
            Err(error) => return Err(error),
        };
        if !value.is_finite() {
            return Err(Error("numeric_overflow".into()));
        }
        Ok(format!("({value})"))
    }
    fn margin_price(&self, cost: &str, rate: &str, context: &Context) -> Result<String, Error> {
        let cost = self.money(cost, true, context)?;
        let remaining = self.rate(rate, true, true, context)?;
        if self.engine.quantity_value(&remaining, "1", context)? == 0.0 {
            return Err(Error("invalid_financial_rate".into()));
        }
        Ok(format!("({cost} / {remaining})"))
    }
    fn tax_profit(
        &self,
        profit: &str,
        rate: &str,
        positive_only: bool,
        context: &Context,
    ) -> Result<String, Error> {
        let remaining = self.rate(rate, true, true, context)?;
        let zero = format!("0 * {profit}");
        if positive_only {
            Ok(format!(
                "(min({profit}, {zero}) + max({profit}, {zero}) * {remaining})"
            ))
        } else if self.engine.quantity_order(profit, &zero, context)? == Ordering::Less {
            // A loss needs an explicit tax policy; do not invent a refund or zero-tax clamp.
            Err(Error("unsupported_financial_parameters".into()))
        } else {
            Ok(format!("({profit} * {remaining})"))
        }
    }
    fn inventory(&self, bought: &str, sold: &str, context: &Context) -> Result<(), Error> {
        if self.engine.quantity_order(sold, bought, context)? == Ordering::Greater {
            Err(Error("invalid_financial_argument".into()))
        } else {
            Ok(())
        }
    }

    fn lower(&self, input: &str, context: &Context) -> Result<Option<String>, Error> {
        let input = input.trim().trim_end_matches(['?', '.']);
        if let Some(expression) = self.lower_inventory(input, context)? {
            return Ok(Some(expression));
        }
        if let Some(expression) = self.lower_balances(input, context)? {
            return Ok(Some(expression));
        }
        if !re!(
            r"(?i)\b(margin|markup|profit|marked up|discount|tax|fee|elasticity|utility|credit)\b"
        )
        .is_match(input)
        {
            return Ok(None);
        }
        if let Some(expression) = self.lower_prices(input, context)? {
            return Ok(Some(expression));
        }
        macro_rules! money {
            ($c:ident, $n:literal) => {
                self.money(&$c[$n], false, context)?
            };
            ($c:ident, $n:literal, positive) => {
                self.money(&$c[$n], true, context)?
            };
        }
        macro_rules! rate {
            ($c:ident, $n:literal) => {
                self.rate(&$c[$n], true, false, context)?
            };
            ($c:ident, $n:literal, markup) => {
                self.rate(&$c[$n], false, false, context)?
            };
            ($c:ident, $n:literal, remaining) => {
                self.rate(&$c[$n], true, true, context)?
            };
        }
        macro_rules! count {
            ($c:ident, $n:literal) => {
                self.count(&$c[$n], context)?
            };
        }
        if let Some(c) = re!(r"(?i)^a product costs (.+?) and sells for (.+?); calculate gross margin percentage and markup percentage$").captures(input) {
            let cost=money!(c,1,positive);
            let sale=money!(c,2,positive);
            let p=profit(&sale,&cost);
            return Ok(Some(summary(&[("margin","p",ratio_percent(&p,&sale)),("markup","p",ratio_percent(&p,&cost))])));
        }
        if let Some(c) =
            re!(r"(?i)^what selling price gives a (.+?)% margin on a (.+?) cost$").captures(input)
        {
            return Ok(Some(self.margin_price(&c[2], &c[1], context)?));
        }
        if let Some(c) =
            re!(r"(?i)^a (.+?) cost is marked up by (.+?)%; what is the selling price$")
                .captures(input)
        {
            let cost = money!(c, 1);
            let markup = rate!(c, 2, markup);
            return Ok(Some(format!("{cost} * (1 + {markup})")));
        }
        if let Some(c) =
            re!(r"(?i)^revenue is (.+?) and cost is (.+?); find profit and profit margin$")
                .captures(input)
        {
            let revenue = money!(c, 1, positive);
            let cost = money!(c, 2);
            let p = profit(&revenue, &cost);
            return Ok(Some(summary(&[
                ("profit", "m", p.clone()),
                ("margin", "p", ratio_percent(&p, &revenue)),
            ])));
        }
        if let Some(c) = re!(r"(?i)^compute after-tax profit on (.+?) revenue, (.+?) costs, and (.+?)% tax on positive profit$").captures(input) {
            let revenue=money!(c,1);
            let cost=money!(c,2);
            return Ok(Some(self.tax_profit(&profit(&revenue,&cost),&c[3],true,context)?));
        }
        if let Some(c) = re!(r"(?i)^markup a (.+?) cost by (.+?)%, discount the resulting price by (.+?)%, then calculate profit and margin$").captures(input) {
            let cost=money!(c,1);
            let markup=rate!(c,2,markup);
            let retained=rate!(c,3,remaining);
            let sale=format!("({cost} * (1 + {markup}) * {retained})");
            self.money(&sale,true,context)?;
            let p=profit(&sale,&cost);
            return Ok(Some(summary(&[("profit","m",p.clone()),("margin","p",ratio_percent(&p,&sale))])));
        }
        if let Some(c) = re!(r"(?i)^a company earns (.+?) revenue, pays (.+?) materials and (.+?) labor, pays a (.+?)% fee on revenue, then (.+?)% tax on remaining profit; calculate net profit and margin$").captures(input) {
            let revenue=money!(c,1,positive);
            let materials=money!(c,2);
            let labor=money!(c,3);
            let retained=rate!(c,4,remaining);
            let p=format!("({revenue} * {retained} - {materials} - {labor})");
            let net=self.tax_profit(&p,&c[5],false,context)?;
            return Ok(Some(summary(&[("net profit","m",net.clone()),("net margin","p",ratio_percent(&net,&revenue))])));
        }
        if let Some(c) = re!(r"(?i)^a shop buys (.+?) units at (.+?) each, sells (.+?) at (.+?) each, and pays a (.+?)% fee on sales; calculate cash profit and margin on sales$").captures(input) {
            let bought=count!(c,1);
            let buy_price=money!(c,2);
            let sold=count!(c,3);
            let sell_price=money!(c,4);
            let retained=rate!(c,5,remaining);
            self.inventory(&bought,&sold,context)?;
            let revenue=format!("({sold} * {sell_price})");
            self.money(&revenue,true,context)?;
            let p=format!("({revenue} * {retained} - {bought} * {buy_price})");
            return Ok(Some(summary(&[("cash profit","m",p.clone()),("margin on sales","p",ratio_percent(&p,&revenue))])));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) item is marked up (.+?)%, then discounted (.+?)%; calculate selling price, profit, and markup on original cost$").captures(input) {
            let cost=money!(c,1,positive);
            let markup=rate!(c,2,markup);
            let retained=rate!(c,3,remaining);
            let sale=format!("({cost} * (1 + {markup}) * {retained})");
            let p=profit(&sale,&cost);
            return Ok(Some(summary(&[("selling price","m",sale),("profit","m",p.clone()),("markup","p",ratio_percent(&p,&cost))])));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) item is marked up (.+?)%; calculate profit as (.+?)% of the selling price$").captures(input) {
            let cost=money!(c,1);
            let markup=rate!(c,2,markup);
            let claimed=rate!(c,3);
            let sale=format!("({cost} * (1 + {markup}))");
            let p=profit(&sale,&cost);
            if self.engine.quantity_order(&p,&format!("{sale} * {claimed}"),context)? != Ordering::Equal {
                return Err(Error("invalid_financial_argument".into()));
            }
            return Ok(Some(p));
        }
        if let Some(c) = re!(r"(?i)^for a (.+?) cost and (.+?) sale, calculate markup percentage using profit divided by sale price and margin using profit divided by cost$").captures(input) {
            let _cost=money!(c,1,positive);
            let _sale=money!(c,2,positive);
            // The supplied denominators explicitly contradict both named definitions.
            return Err(Error("invalid_financial_argument".into()));
        }
        if let Some(c) = re!(r"(?i)^for a (.+?) cost, set a (.+?)% profit margin and then apply a (.+?)% markup to that selling price; calculate the result$").captures(input) {
            let sale=self.margin_price(&c[1],&c[2],context)?;
            let markup=rate!(c,3,markup);
            return Ok(Some(format!("{sale} * (1 + {markup})")));
        }
        if let Some(c) = re!(r"(?i)^a shop buys goods for (.+?), adds (.+?)% markup, discounts the sale price by (.+?)%, then pays a (.+?)% fee on proceeds; calculate profit$").captures(input) {
            let cost=money!(c,1);
            let markup=rate!(c,2,markup);
            let discounted=rate!(c,3,remaining);
            let retained=rate!(c,4,remaining);
            return Ok(Some(format!("({cost} * (1 + {markup}) * {discounted} * {retained}) - {cost}")));
        }
        if let Some(c) = re!(r"(?i)^a product sells (.+?) units at (.+?) with a (.+?)% fee and costs (.+?) per unit; calculate profit and margin after fees$").captures(input) {
            let units=count!(c,1);
            let price=money!(c,2);
            let retained=rate!(c,3,remaining);
            let cost=money!(c,4);
            let revenue=format!("({units} * {price})");
            self.money(&revenue,true,context)?;
            let p=format!("({revenue} * {retained} - {units} * {cost})");
            return Ok(Some(summary(&[("profit","m",p.clone()),("margin after fees","p",ratio_percent(&p,&revenue))])));
        }
        if let Some(c) = re!(r"(?i)^a business has (.+?) revenue, (.+?) cost, (.+?) overhead, and (.+?)% tax on profit after overhead; find net profit$").captures(input) {
            let revenue=money!(c,1);
            let cost=money!(c,2);
            let overhead=money!(c,3);
            let p=format!("({revenue} - {cost} - {overhead})");
            return Ok(Some(self.tax_profit(&p,&c[4],false,context)?));
        }
        if let Some(c) = re!(
            r"(?i)^a (.+?)% markup on cost produces a (.+?) price; calculate cost and gross margin$"
        )
        .captures(input)
        {
            let markup = rate!(c, 1, markup);
            let sale = money!(c, 2, positive);
            let cost = format!("({sale} / (1 + {markup}))");
            let p = profit(&sale, &cost);
            return Ok(Some(summary(&[
                ("cost", "m", cost),
                ("margin", "p", ratio_percent(&p, &sale)),
            ])));
        }
        if let Some(c) = re!(r"(?i)^a company sells (.+?) units at (.+?), incurs (.+?) variable cost each and (.+?) fixed cost; calculate profit and margin$").captures(input) {
            let units=count!(c,1);
            let price=money!(c,2);
            let variable=money!(c,3);
            let fixed=money!(c,4);
            let revenue=format!("({units} * {price})");
            self.money(&revenue,true,context)?;
            let p=format!("({revenue} - {units} * {variable} - {fixed})");
            return Ok(Some(summary(&[("profit","m",p.clone()),("margin","p",ratio_percent(&p,&revenue))])));
        }
        if let Some(c) = re!(r"(?i)^a shop buys (.+?) items at (.+?) each, sells (.+?) at (.+?) each, and pays (.+?) fixed fees; calculate realized profit on sold items$").captures(input) {
            let bought=count!(c,1);
            let cost=money!(c,2);
            let sold=count!(c,3);
            let price=money!(c,4);
            let fixed=money!(c,5);
            self.inventory(&bought,&sold,context)?;
            return Ok(Some(format!("({sold} * ({price} - {cost})) - {fixed}")));
        }
        if let Some(c) = re!(r"(?i)^an? (.+?) cost is sold at (.+?); calculate margin, then reduce the sale price by (.+?)% and recalculate margin$").captures(input) {
            let cost=money!(c,1);
            let before=money!(c,2,positive);
            let retained=rate!(c,3,remaining);
            let after=format!("({before} * {retained})");
            self.money(&after,true,context)?;
            return Ok(Some(summary(&[("margin before discount","p",ratio_percent(&profit(&before,&cost),&before)),("margin after discount","p",ratio_percent(&profit(&after,&cost),&after))])));
        }
        if let Some(c) = re!(r"(?i)^a service earns (.+?) revenue, pays (.+?) labor, a (.+?)% revenue fee, and (.+?)% tax on profit after the fee; calculate net profit$").captures(input) {
            let revenue=money!(c,1);
            let labor=money!(c,2);
            let retained=rate!(c,3,remaining);
            let p=format!("({revenue} * {retained} - {labor})");
            return Ok(Some(self.tax_profit(&p,&c[4],false,context)?));
        }
        if let Some(c) = re!(r"(?i)^for a (.+?) cost, calculate selling price at (.+?)% margin, then apply a (.+?)% sales fee; find profit after fee and margin on revenue$").captures(input) {
            let cost=money!(c,1);
            let sale=self.margin_price(&c[1],&c[2],context)?;
            let retained=rate!(c,3,remaining);
            let p=format!("({sale} * {retained} - {cost})");
            return Ok(Some(summary(&[("selling price","m",sale.clone()),("profit after fee","m",p.clone()),("margin on revenue","p",ratio_percent(&p,&sale))])));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) project has (.+?)% fee on revenue, (.+?) costs, and (.+?)% tax on positive profit after fee; calculate net profit and net margin$").captures(input) {
            let revenue=money!(c,1,positive);
            let retained=rate!(c,2,remaining);
            let cost=money!(c,3);
            let p=format!("({revenue} * {retained} - {cost})");
            let net=self.tax_profit(&p,&c[4],true,context)?;
            return Ok(Some(summary(&[("net profit","m",net.clone()),("net margin","p",ratio_percent(&net,&revenue))])));
        }
        Ok(None)
    }
}