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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
//! Rate definitions and requested report roles; arithmetic belongs to the scalar AST.
use crate::{Context, Error, Outcome, Plugin, re};
use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::{One, Signed, ToPrimitive, Zero};
use std::cmp::Ordering;

pub(super) struct Definition {
    basis: Option<f64>,
    value: BigRational,
}

pub(super) struct ReportGoal {
    pub balance: bool,
    pub interest: bool,
    pub loss: bool,
}

fn financial_coordinate(
    input: &str,
    ordinal: bool,
    engine: &super::super::compositions::Compositions,
    context: &Context,
) -> Result<super::super::model_coordinates::Coordinate, Error> {
    let input = input.trim().to_ascii_lowercase();
    // Ordinals name the annual posting boundary; cardinals use the existing
    // language normalizer before the shared exact scalar reader.
    let cardinal = if ordinal {
        match input.as_str() {
            "first" => "one",
            "second" => "two",
            "third" => "three",
            "fourth" => "four",
            "fifth" => "five",
            "sixth" => "six",
            "seventh" => "seven",
            "eighth" => "eight",
            "ninth" => "nine",
            "tenth" => "ten",
            _ => re!(r"^([0-9]+)(?:st|nd|rd|th)$")
                .captures(&input)
                .map(|c| c.get(1).unwrap().as_str())
                .unwrap_or(&input),
        }
    } else {
        &input
    };
    let normalized = super::super::language::Language::default()
        .rewrite(cardinal, context)
        .transpose()?
        .unwrap_or_else(|| cardinal.into());
    let period = super::super::model_coordinates::read(&normalized, "1", engine, context)?;
    if period.value.is_negative() || ordinal && !period.value.is_integer() {
        return Err(Error("invalid_duration".into()));
    }
    Ok(period)
}

fn financial_period(
    input: &str,
    ordinal: bool,
    engine: &super::super::compositions::Compositions,
    context: &Context,
) -> Result<BigRational, Error> {
    financial_coordinate(input, ordinal, engine, context).map(|coordinate| coordinate.value)
}

fn finite_coordinate(value: &BigRational) -> Result<f64, Error> {
    let coordinate = value
        .to_f64()
        .filter(|value| value.is_finite())
        .ok_or_else(|| Error("numeric_overflow".into()))?;
    if coordinate == 0.0 && !value.is_zero() {
        return Err(Error("numeric_underflow".into()));
    }
    Ok(coordinate)
}

fn exact_monthly_balance(
    opening: &BigRational,
    fee: &BigRational,
    factor: &BigRational,
    months: &BigInt,
) -> Result<BigRational, Error> {
    let bounded = super::super::model_coordinates::bounded;
    if months.is_zero() {
        return Ok(opening.clone());
    }
    if factor.is_zero() {
        return Ok(BigRational::zero());
    }
    if factor.is_one() {
        return bounded(opening - BigRational::from_integer(months.clone()) * fee);
    }
    let stationary = bounded(factor * fee / (factor - BigRational::one()))?;
    let departure = bounded(opening - &stationary)?;
    if departure.is_zero() {
        return Ok(stationary);
    }
    let mut exponent = months.clone();
    let mut power = factor.clone();
    let mut product = BigRational::one();
    while !exponent.is_zero() {
        if (&exponent & BigInt::one()) == BigInt::one() {
            product = bounded(product * &power)?;
        }
        exponent >>= 1;
        if !exponent.is_zero() {
            power = bounded(&power * &power)?;
        }
    }
    bounded(stationary + bounded(departure * product)?)
}

fn periodic_log_factor(
    percent: &str,
    engine: &super::super::compositions::Compositions,
    context: &Context,
) -> Result<f64, Error> {
    let rate = super::super::model_coordinates::read(percent, "1", engine, context)?.value
        / BigRational::from_integer(100.into());
    if rate <= -BigRational::one() {
        return Err(Error("invalid_financial_rate".into()));
    }
    let factor = super::super::model_coordinates::bounded(BigRational::one() + &rate)?;
    let factor = finite_coordinate(&factor)?;
    // Preserve a positive authored 1+r near -100%, and retain tiny rates when
    // its binary64 factor rounds to one.
    Ok(if factor == 1.0 {
        finite_coordinate(&rate)?.ln_1p()
    } else {
        factor.ln()
    })
}

fn financial_list(input: &str) -> Result<Vec<String>, Error> {
    let input = re!(r"(?i),?\s+and\s+").replace_all(input, ", ");
    let mut rest = input.as_ref();
    let mut fields = Vec::new();
    while let Some((left, right)) = super::super::syntax::split_last(rest, &[","]) {
        fields.push(right.trim().to_string());
        if fields.len() >= 256 {
            return Err(Error("expression_too_complex".into()));
        }
        rest = left;
    }
    fields.push(rest.trim().to_string());
    if fields.iter().any(String::is_empty) {
        return Err(Error("invalid_financial_argument".into()));
    }
    fields.reverse();
    Ok(fields)
}

/// A supplied annual return list defines consecutive factors, not a nominal rate.
pub(super) fn annual_returns(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']).replace('−', "-");
    let c = re!(r"(?i)^a (?:fund|investment|account) starts (?:at|with) (.+?) and has annual returns (.+?)(?: in that order)?; report (.+?) over (.+?) years?$")
        .captures(&input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        let (principal_exact, code) = super::nonnegative_money_coordinate(&c[1], &engine, context)?;
        let rates = financial_list(&c[2])?;
        let count = financial_period(&c[4], false, &engine, context)?;
        if !count.is_integer()
            || count.is_zero()
            || count != BigRational::from_integer(rates.len().into())
        {
            return Err(Error("invalid_duration".into()));
        }
        let goals = financial_list(&c[3])?;
        if goals.len() != 2 {
            return Err(Error("invalid_financial_argument".into()));
        }
        let mut seen = Vec::new();
        for goal in &goals {
            let goal = goal.to_ascii_lowercase();
            if !matches!(
                goal.as_str(),
                "ending value" | "geometric mean annual return"
            ) || seen.contains(&goal)
            {
                return Err(Error("invalid_financial_argument".into()));
            }
            seen.push(goal);
        }
        let bounded = super::super::model_coordinates::bounded;
        let mut factors = Vec::new();
        let mut authored = principal_exact.authored;
        let mut positive_rates = Vec::new();
        for rate in rates {
            let c = re!(r"(?i)^(.+?)(?:%| percent)$")
                .captures(&rate)
                .ok_or_else(|| Error("invalid_financial_rate".into()))?;
            let rate = super::super::model_coordinates::read(&c[1], "1", &engine, context)?;
            authored &= rate.authored;
            let factor =
                bounded(BigRational::one() + rate.value / BigRational::from_integer(100.into()))?;
            if factor.is_negative() {
                return Err(Error("invalid_financial_rate".into()));
            }
            if !factor.is_zero() {
                positive_rates.push(c[1].to_owned());
            }
            factors.push(factor);
        }
        let zero = factors.iter().any(Zero::is_zero);
        let gross = if zero {
            BigRational::zero()
        } else {
            factors
                .into_iter()
                .try_fold(BigRational::one(), |product, factor| {
                    bounded(product * factor)
                })?
        };
        let ending = bounded(principal_exact.value * gross)?;
        let ending = if authored {
            format!("(rational({},{}) {code})", ending.numer(), ending.denom())
        } else {
            format!("(real({:e}) {code})", finite_coordinate(&ending)?)
        };
        let mean = if zero {
            -1.0
        } else {
            let mut log_sum = BigRational::zero();
            for rate in positive_rates {
                let log = periodic_log_factor(&rate, &engine, context)?;
                log_sum = bounded(
                    log_sum
                        + BigRational::from_float(log)
                            .ok_or_else(|| Error("numeric_overflow".into()))?,
                )?;
            }
            super::Growth {
                principal: 1.0,
                code,
                annual_rate: 0.0,
                years: 1.0,
                frequency: 1.0,
                goal: super::Goal::Interest,
            }
            .value_for_log_periods(finite_coordinate(&(log_sum / count))?, 1.0)?
        };
        // Validate final money without feeding its formatted display back into
        // arithmetic. Zero principal never enters ending/principal division.
        engine.evaluate_money(&ending, context)?;
        let fields = seen
            .into_iter()
            .map(|goal| match goal.as_str() {
                "ending value" => format!("{goal}|{ending}"),
                _ => format!("{goal}|real({mean:e})"),
            })
            .collect::<Vec<_>>();
        let report = format!("finance_annual_report({})", fields.join(";"));
        if report.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        Ok(report)
    })())
}

fn discounted_receipts(
    receipts: &[(super::Growth, BigRational)],
    log_factor: f64,
) -> Result<BigRational, Error> {
    let mut present_value = BigRational::zero();
    for (receipt, authored) in receipts {
        let value = if log_factor == 0.0 {
            // At zero rate all authored receipts retain their exact coordinate;
            // an endpoint identity must not depend on decimal-to-float roundoff.
            authored.clone()
        } else {
            // Discounts remain the shared binary64 Growth computation. Sum its
            // actual coordinates as rationals to avoid an overflowing positive
            // subtotal before comparing it with the finite initial cost.
            let value =
                BigRational::from_float(receipt.value_for_log_periods(log_factor, receipt.years)?)
                    .ok_or_else(|| Error("numeric_overflow".into()))?;
            if authored.is_negative() {
                -value
            } else {
                value
            }
        };
        present_value = super::super::model_coordinates::bounded(present_value + value)?;
    }
    Ok(present_value)
}

fn cashflow_sign(
    cost: &BigRational,
    receipts: &[(super::Growth, BigRational)],
    rate: f64,
) -> Result<Ordering, Error> {
    Ok(discounted_receipts(receipts, rate.ln_1p())?.cmp(cost))
}

/// A complete signed schedule at a supplied effective rate is a forward value,
/// rather than the monotone nonnegative-receipt model used for inverse IRR.
pub(super) fn cashflow_npv(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let c = re!(r"(?i)^for the (.+?) cash flows (.+?), (?:compute|calculate|find) NPV at an effective annual discount rate of (.+?)(?:%| percent) and report the sign$")
        .captures(input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        let count = financial_period(&c[1], false, &engine, context)?;
        let count = count
            .to_integer()
            .to_usize()
            .filter(|_| count.is_integer())
            .filter(|n| (1..=256).contains(n))
            .ok_or_else(|| Error("invalid_financial_argument".into()))?;
        let clauses = financial_list(&c[2])?;
        if clauses.len() != count {
            return Err(Error("invalid_financial_argument".into()));
        }
        let rate = super::super::model_coordinates::read(&c[3], "1", &engine, context)?;
        let rate_value = &rate.value / BigRational::from_integer(100.into());
        let factor = super::super::model_coordinates::bounded(BigRational::one() + &rate_value)?;
        if factor <= BigRational::zero() {
            return Err(Error("invalid_financial_rate".into()));
        }
        let mut authored = rate.authored;
        let mut receipts = Vec::with_capacity(count);
        let mut years = Vec::with_capacity(count);
        let mut initial_count = 0;
        for clause in clauses {
            let c = re!(r"(?i)^(.+?) at (?:time (.+?)|(?:the )?end of year (.+?))$")
                .captures(&clause)
                .ok_or_else(|| Error("invalid_financial_argument".into()))?;
            let amount = super::super::model_coordinates::read(&c[1], "1", &engine, context)?;
            let year = financial_coordinate(
                c.get(2).or_else(|| c.get(3)).unwrap().as_str(),
                false,
                &engine,
                context,
            )?;
            if !year.value.is_integer()
                || c.get(2).is_some() && !year.value.is_zero()
                || c.get(3).is_some() && year.value.is_zero()
            {
                return Err(Error("invalid_duration".into()));
            }
            initial_count += usize::from(c.get(2).is_some());
            authored &= amount.authored && year.authored;
            let receipt = super::Growth {
                principal: finite_coordinate(&amount.value.abs())?,
                code: "",
                annual_rate: 0.0,
                years: finite_coordinate(&year.value)?,
                frequency: 1.0,
                goal: super::Goal::Principal,
            };
            receipt.validate()?;
            receipts.push((receipt, amount.value));
            years.push(year.value);
        }
        if initial_count != 1 {
            return Err(Error("invalid_financial_argument".into()));
        }
        let value = if authored {
            let mut sum = BigRational::zero();
            for ((_, amount), year) in receipts.iter().zip(years) {
                let value = if amount.is_zero() || factor.is_one() || year.is_zero() {
                    amount.clone()
                } else {
                    let power = year
                        .to_integer()
                        .to_i32()
                        .ok_or_else(|| Error("integer_limit".into()))?;
                    let bits = factor.numer().bits().max(factor.denom().bits());
                    if bits * power as u64 > 65_536 {
                        return Err(Error("integer_limit".into()));
                    }
                    super::super::model_coordinates::bounded(amount / factor.pow(power))?
                };
                sum = super::super::model_coordinates::bounded(sum + value)?;
            }
            format!("rational({},{})", sum.numer(), sum.denom())
        } else {
            let sum =
                discounted_receipts(&receipts, periodic_log_factor(&c[3], &engine, context)?)?;
            format!("real({:e})", finite_coordinate(&sum)?)
        };
        let result = format!("finance_npv_report({value})");
        if result.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        Ok(result)
    })())
}

/// Positive receipts at explicit year ends give a strictly decreasing NPV.
/// Only that complete monotone model owns this bounded effective-rate search.
pub(super) fn cashflow_irr(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let c = re!(r"(?i)^a project costs (.+?) now and pays (.+?) at the ends of years (.+?); find the annual effective rate making net present value zero between (.+?) and (.+?) percent$")
        .captures(input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        engine.evaluate_money(&c[1], context)?;
        let (_, code) = super::signed_amount(&c[1])
            .filter(|(value, code)| *value > 0.0 && !code.is_empty())
            .ok_or_else(|| Error("invalid_financial_argument".into()))?;
        let number = re!(r"(?i)[+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?")
            .find(&c[1])
            .ok_or_else(|| Error("invalid_financial_argument".into()))?;
        let cost =
            super::super::model_coordinates::read(number.as_str(), "1", &engine, context)?.value;
        let (values, receipt_code) = c[2]
            .char_indices()
            .filter_map(|(at, ch)| {
                if !ch.is_whitespace() {
                    return None;
                }
                super::super::finance::currency(c[2][at..].trim())
                    .map(|code| (c[2][..at].trim(), code))
            })
            .next()
            .ok_or_else(|| Error("invalid_financial_argument".into()))?;
        if receipt_code != code {
            return Err(Error("incompatible_units".into()));
        }
        let values = financial_list(values)?;
        let years = financial_list(&c[3])?;
        if values.len() != years.len() {
            return Err(Error("invalid_financial_argument".into()));
        }
        let mut receipts = Vec::with_capacity(values.len());
        for (amount, year) in values.iter().zip(years) {
            let amount =
                super::super::model_coordinates::read(amount, "1", &engine, context)?.value;
            if amount.is_negative() {
                return Err(Error("invalid_financial_argument".into()));
            }
            let year = financial_period(&year, false, &engine, context)?;
            if year.is_zero() || !year.is_integer() {
                return Err(Error("invalid_duration".into()));
            }
            let receipt = super::Growth {
                principal: finite_coordinate(&amount)?,
                code,
                annual_rate: 0.0,
                years: finite_coordinate(&year)?,
                frequency: 1.0,
                goal: super::Goal::Principal,
            };
            receipt.validate()?;
            receipts.push((receipt, amount));
        }
        if receipts.iter().all(|(_, amount)| amount.is_zero()) {
            return Err(Error("invalid_financial_argument".into()));
        }
        let hundred = BigRational::from_integer(100.into());
        let left =
            super::super::model_coordinates::read(&c[4], "1", &engine, context)?.value / &hundred;
        let right =
            super::super::model_coordinates::read(&c[5], "1", &engine, context)?.value / hundred;
        if left.is_negative() || right <= left {
            return Err(Error("invalid_financial_rate".into()));
        }
        let (mut left, mut right) = (finite_coordinate(&left)?, finite_coordinate(&right)?);
        if right <= left {
            return Err(Error("invalid_financial_rate".into()));
        }
        let lower = cashflow_sign(&cost, &receipts, left)?;
        let upper = cashflow_sign(&cost, &receipts, right)?;
        let rate = if lower == Ordering::Equal {
            left
        } else if upper == Ordering::Equal {
            right
        } else {
            if lower != Ordering::Greater || upper != Ordering::Less {
                return Err(Error("no_financial_solution".into()));
            }
            // The full binary64 exponent span plus significand fits this finite
            // bound. Stop at representational exhaustion, never an NPV epsilon.
            for _ in 0..2176 {
                let middle = left + (right - left) * 0.5;
                if middle == left || middle == right {
                    break;
                }
                match cashflow_sign(&cost, &receipts, middle)? {
                    Ordering::Greater => left = middle,
                    Ordering::Less => right = middle,
                    Ordering::Equal => {
                        left = middle;
                        right = middle;
                        break;
                    }
                }
            }
            left + (right - left) * 0.5
        };
        Ok(format!("real({rate:e}) as percent"))
    })())
}

/// A loan's equal payments are the inverse of the same end-period present-value
/// factor used for coupons. The first payment is explicitly one month later.
pub(super) fn monthly_loan(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let c = re!(r"(?i)^a (.+?) loan is repaid by (.+?) equal end-of-month payments at (.+?)% monthly interest, first payment one month after origination; report the payment to the nearest cent$")
        .captures(input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        let count = financial_period(&c[2], false, &engine, context)?;
        if count.is_zero() || !count.is_integer() {
            return Err(Error("invalid_duration".into()));
        }
        let periods = finite_coordinate(&count)?;
        let log_factor = periodic_log_factor(&c[3], &engine, context)?;
        engine.evaluate_money(&c[1], context)?;
        let (principal, code) = super::signed_amount(&c[1])
            .filter(|(_, code)| !code.is_empty())
            .ok_or_else(|| Error("invalid_financial_argument".into()))?;
        let growth = super::Growth {
            principal,
            code,
            annual_rate: 0.0,
            years: periods,
            frequency: 1.0,
            goal: super::Goal::Principal,
        };
        growth.validate()?;
        let unit_present_value = super::Growth {
            principal: 1.0,
            ..growth
        }
        .recurring_present_value(periods, log_factor)?;
        let payment = principal / unit_present_value;
        if !payment.is_finite() {
            return Err(Error("numeric_overflow".into()));
        }
        if payment == 0.0 && principal != 0.0 {
            return Err(Error("numeric_underflow".into()));
        }
        let expression = format!("({payment} {code})");
        engine.evaluate_money(&expression, context)?;
        Ok(expression)
    })())
}

/// End-period coupons and redemption share the explicitly supplied periodic
/// effective discount rate, with redemption at the final coupon's boundary.
pub(super) fn coupon_bond(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let c = re!(r"(?i)^a bond pays (?:a )?(.+?) coupon every (.+?) months? for (.+?) years? and repays (.+?) with the final coupon; discount all cash flows at an effective (.+?)% per (.+?)[- ]month period to find price$")
        .captures(input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        let interval = financial_period(&c[2], false, &engine, context)?;
        let years = financial_period(&c[3], false, &engine, context)?;
        let rate_interval = financial_period(&c[6], false, &engine, context)?;
        if interval.is_zero() || years.is_zero() {
            return Err(Error("invalid_duration".into()));
        }
        if rate_interval != interval {
            return Err(Error("invalid_financial_rate".into()));
        }
        // Authored financial years contain twelve months; physical/calendar
        // duration conversion would give the wrong coupon cardinality.
        let count = super::super::model_coordinates::bounded(
            years * BigRational::from_integer(12.into()) / interval,
        )?;
        if !count.is_integer() {
            return Err(Error("invalid_duration".into()));
        }
        let periods = finite_coordinate(&count)?;
        let log_factor = periodic_log_factor(&c[5], &engine, context)?;
        let cashflow = |input: &str| -> Result<super::Growth, Error> {
            // Hyphenated money adjectives are normalized only inside the
            // complete monetary role, with a recognized currency suffix.
            let amount = if let Some((number, currency)) = input.rsplit_once('-')
                && super::super::finance::currency(currency).is_some()
                && super::super::integer_queries::ratio_value(number).is_ok()
            {
                format!("{number} {currency}")
            } else {
                input.to_string()
            };
            engine.evaluate_money(&amount, context)?;
            let (principal, code) = super::signed_amount(&amount)
                .filter(|(_, code)| !code.is_empty())
                .ok_or_else(|| Error("invalid_financial_argument".into()))?;
            let growth = super::Growth {
                principal,
                code,
                // The validated factor's log owns this discount model. A zero
                // placeholder keeps ordinary rate-based Growth callers intact.
                annual_rate: 0.0,
                years: periods,
                frequency: 1.0,
                goal: super::Goal::Principal,
            };
            growth.validate()?;
            Ok(growth)
        };
        let coupon = cashflow(&c[1])?;
        let redemption = cashflow(&c[4])?;
        let expression = format!(
            "(({} {}) + ({} {}))",
            coupon.recurring_present_value(periods, log_factor)?,
            coupon.code,
            redemption.value_for_log_periods(log_factor, periods)?,
            redemption.code,
        );
        engine.evaluate_money(&expression, context)?;
        Ok(expression)
    })())
}

/// Two explicit deposits share an annual valuation boundary. Neither deposit
/// earns interest before its own supplied investment time.
pub(super) fn timed_deposits(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let c = re!(r"(?i)^if i (?:invest|deposit) (.+?) now and another (.+?) exactly (.+?) years? later, at (.+?)% annual compounding, what is the value immediately after the (.+?) year[’']s interest is applied$")
        .captures(input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        let delay = financial_period(&c[3], false, &engine, context)?;
        let horizon = financial_period(&c[5], true, &engine, context)?;
        if delay > horizon {
            return Err(Error("invalid_duration".into()));
        }
        let remaining = super::super::model_coordinates::bounded(&horizon - delay)?;
        let annual = super::super::model_coordinates::read(&c[4], "1", &engine, context)?.value
            / BigRational::from_integer(100.into());
        let annual_rate = finite_coordinate(&annual)?;
        let balance = |amount: &str, years: &BigRational| -> Result<String, Error> {
            engine.evaluate_money(amount, context)?;
            let (principal, code) = super::signed_amount(amount)
                .filter(|(_, code)| !code.is_empty())
                .ok_or_else(|| Error("invalid_financial_argument".into()))?;
            super::Growth {
                principal,
                code,
                annual_rate,
                years: finite_coordinate(years)?,
                frequency: 1.0,
                goal: super::Goal::Balance,
            }
            .literal()
        };
        let expression = format!(
            "({} + {})",
            balance(&c[1], &horizon)?,
            balance(&c[2], &remaining)?
        );
        // Keep unrounded Growth coordinates and let the existing money owner
        // validate currency compatibility and format only the final total.
        engine.evaluate_money(&expression, context)?;
        Ok(expression)
    })())
}

/// Interest precedes both recurring cashflows, including the final month's fee
/// and deposit. Separate annuities keep each supplied monetary role validated.
pub(super) fn monthly_account(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let c = re!(r"(?i)^an? account charges (?:a )?(.+?) monthly fee and earns (.+?)% monthly; starting with (.+?) and making (.+?) deposits at each month-end for (.+?) months?, (?:calculate|find) the closing balance after the last fee and deposit, with interest applied before fee and deposit each month$")
        .captures(input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        let count = financial_period(&c[5], false, &engine, context)?;
        if !count.is_integer() {
            return Err(Error("invalid_duration".into()));
        }
        let periods = finite_coordinate(&count)?;
        let rate = super::super::model_coordinates::read(&c[2], "1", &engine, context)?.value
            / BigRational::from_integer(100.into());
        let monthly_rate = finite_coordinate(&rate)?;
        let growth = |input: &str| -> Result<super::Growth, Error> {
            engine.evaluate_money(input, context)?;
            let (principal, code) = super::signed_amount(input)
                .filter(|(_, code)| !code.is_empty())
                .ok_or_else(|| Error("invalid_financial_argument".into()))?;
            // The shared growth kernel uses one supplied monthly period as its
            // time coordinate; no nominal-annual rate is inferred or multiplied.
            let growth = super::Growth {
                principal,
                code,
                annual_rate: monthly_rate,
                years: periods,
                frequency: 1.0,
                goal: super::Goal::Interest,
            };
            growth.validate()?;
            Ok(growth)
        };
        let opening = growth(&c[3])?;
        let fee = growth(&c[1])?;
        let deposit = growth(&c[4])?;
        let opening = super::Growth {
            goal: super::Goal::Balance,
            ..opening
        }
        .literal()?;
        let expression = format!(
            "({opening} + ({} {}) - ({} {}))",
            deposit.recurring_deposit_value(periods)?,
            deposit.code,
            fee.recurring_deposit_value(periods)?,
            fee.code,
        );
        // Validate the complete currency sum without using its formatted display.
        engine.evaluate_money(&expression, context)?;
        Ok(expression)
    })())
}

/// One complete month earns interest on the opening balance before its fee.
pub(super) fn one_month_interest_then_fee(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let c = re!(r"(?is)^compute the one-month ending amount from (.+?) at (.+?)% monthly interest when a (.+?) fee is deducted only after interest has been applied to the opening balance$")
        .captures(input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        let (opening, code) = super::nonnegative_money_coordinate(&c[1], &engine, context)?;
        let (fee, fee_code) = super::nonnegative_money_coordinate(&c[3], &engine, context)?;
        let normalized_fee = super::normalize_grouped_money(&c[3])
            .ok_or_else(|| Error("invalid_financial_argument".into()))?;
        engine.quantity_value(&normalized_fee, code, context)?;
        let fee = super::money_in_currency(fee.value, fee_code, code, context)?;
        let rate = super::super::model_coordinates::read(&c[2], "1", &engine, context)?.value
            / BigRational::from_integer(100.into());
        let gross = super::super::model_coordinates::bounded(BigRational::one() + rate)?;
        if gross.is_negative() {
            return Err(Error("invalid_financial_rate".into()));
        }
        let post_interest = super::super::model_coordinates::bounded(opening.value * gross)?;
        if fee > post_interest {
            return Err(Error("invalid_financial_argument".into()));
        }
        let ending = super::super::model_coordinates::bounded(post_interest - fee)?;
        let expression = format!("(rational({},{}) {code})", ending.numer(), ending.denom());
        engine.evaluate_money(&expression, context)?;
        Ok(expression)
    })())
}

/// The fee is taken at the start of each month; the remaining balance earns
/// that month's supplied rate. Exact affine coordinates retain pre-fee checks.
pub(super) fn monthly_fee_before_interest(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let c = re!(r"(?is)^an? account charges (?:a )?(.+?) monthly fee and earns (.+?)% interest monthly on the balance after the fee\. starting at (.+?), what is the balance after (.+?) months?$")
        .captures(input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        let count = financial_period(&c[4], false, &engine, context)?;
        if !count.is_integer() {
            return Err(Error("invalid_duration".into()));
        }
        let periods = finite_coordinate(&count)?;
        if BigRational::from_float(periods).as_ref() != Some(&count) {
            return Err(Error("integer_limit".into()));
        }
        let (opening_exact, code) = super::nonnegative_money_coordinate(&c[3], &engine, context)?;
        let (fee_exact, fee_code) = super::nonnegative_money_coordinate(&c[1], &engine, context)?;
        let normalized_fee = super::normalize_grouped_money(&c[1])
            .ok_or_else(|| Error("invalid_financial_argument".into()))?;
        engine.quantity_value(&normalized_fee, code, context)?;
        let fee = super::money_in_currency(fee_exact.value, fee_code, code, context)?;
        let rate = super::super::model_coordinates::read(&c[2], "1", &engine, context)?.value
            / BigRational::from_integer(100.into());
        let gross = super::super::model_coordinates::bounded(BigRational::one() + &rate)?;
        if gross.is_negative() {
            return Err(Error("invalid_financial_rate".into()));
        }
        let months = count.to_integer();
        if !months.is_zero() && opening_exact.value < fee {
            return Err(Error("invalid_financial_argument".into()));
        }
        // For nonnegative gross factor and fee, this affine recurrence is
        // monotone. Check the last pre-fee endpoint exactly, without a loop.
        if months > BigInt::one()
            && exact_monthly_balance(
                &opening_exact.value,
                &fee,
                &gross,
                &(&months - BigInt::one()),
            )? < fee
        {
            return Err(Error("invalid_financial_argument".into()));
        }
        let ending = exact_monthly_balance(&opening_exact.value, &fee, &gross, &months)?;
        let expression = format!("(rational({},{}) {code})", ending.numer(), ending.denom());
        engine.evaluate_money(&expression, context)?;
        Ok(expression)
    })())
}

/// Ordinary annuity timing: the last deposit has earned no interest yet.
pub(super) fn monthly_deposits(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let c = re!(r"(?i)^a (?:customer|person|saver) deposits (.+?) at the end of each month for (.+?) months? into an account earning (.+?)% nominal annual interest compounded monthly; (?:what is|find|calculate) (?:the )?accumulated value immediately after the last deposit$")
        .captures(input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        engine.evaluate_money(&c[1], context)?;
        let (principal, code) = super::signed_amount(&c[1])
            .filter(|(_, code)| !code.is_empty())
            .ok_or_else(|| Error("invalid_financial_argument".into()))?;
        let periods = super::super::integer_queries::value(&c[2])?;
        if periods <= BigInt::zero() {
            return Err(Error("invalid_duration".into()));
        }
        let periods = periods
            .to_f64()
            .filter(|value| value.is_finite())
            .ok_or_else(|| Error("numeric_overflow".into()))?;
        let rate = super::super::model_coordinates::read(&c[3], "1", &engine, context)?;
        let annual = rate.value / BigRational::from_integer(100.into());
        let annual_rate = annual
            .to_f64()
            .filter(|value| value.is_finite())
            .ok_or_else(|| Error("numeric_overflow".into()))?;
        if annual_rate == 0.0 && !annual.is_zero() {
            return Err(Error("numeric_underflow".into()));
        }
        let growth = super::Growth {
            principal,
            code,
            annual_rate,
            years: periods / 12.0,
            frequency: 12.0,
            goal: super::Goal::Interest,
        };
        let value = growth.recurring_deposit_value(periods)?;
        Ok(format!("({value} {code})"))
    })())
}

/// Supplied months are fractions of an annual simple-interest period, rather
/// than calendar endpoints. Retain the original principal until money display.
pub(super) fn simple_interest(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let c = re!(r"(?i)^a (.+?) (?:balance|principal|investment|account) earns (.+?)% simple annual interest for (.+?) (years?|months?); how much interest (?:accrues|is accrued|is earned)$")
        .captures(input)?;
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let engine = super::super::compositions::Compositions::default();
        engine.evaluate_money(&c[1], context)?;
        if engine.quantity_order(&c[1], &format!("0 * ({})", &c[1]), context)?
            == std::cmp::Ordering::Less
        {
            return Err(Error("invalid_financial_argument".into()));
        }
        let rate = super::super::model_coordinates::read(&c[2], "1", &engine, context)?;
        let duration = super::super::model_coordinates::read(&c[3], "1", &engine, context)?;
        if rate.value.is_negative() {
            return Err(Error("invalid_financial_rate".into()));
        }
        if duration.value.is_negative() {
            return Err(Error("invalid_duration".into()));
        }
        let periods = if c[4].to_ascii_lowercase().starts_with("month") {
            12
        } else {
            1
        };
        let factor = super::super::model_coordinates::bounded(
            rate.value * duration.value / BigRational::from_integer((100 * periods).into()),
        )?;
        let factor = format!("rational({},{})", factor.numer(), factor.denom());
        let factor = if rate.authored && duration.authored {
            factor
        } else {
            format!("real({factor})")
        };
        let expression = format!("(({}) * {factor})", &c[1]);
        if expression.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        // Validate the full typed monetary formula; its display is never reused.
        engine.evaluate_money(&expression, context)?;
        Ok(expression)
    })())
}

/// A supplied simple-interest period is evaluated on the stated side of the fee.
/// The day/year ratio is authored, so no calendar or nominal-day convention is inferred.
struct SuppliedDayInterestRoles {
    opening: String,
    fees: Vec<(String, bool)>,
    rate: String,
    elapsed_days: String,
    basis_days: String,
    allow_negative: bool,
}

/// Validate the complete wording after exact role spans have been identified.
/// A role may change its numeric expression without loosening the stage order.
fn supplied_role_source(input: &str, mut spans: Vec<(usize, usize, &str)>) -> Option<String> {
    if input.contains('\0') {
        return None;
    }
    spans.sort_by_key(|span| span.0);
    if spans.windows(2).any(|pair| pair[0].1 > pair[1].0) {
        return None;
    }
    let mut source = input.to_owned();
    for (start, end, role) in spans.into_iter().rev() {
        source.replace_range(start..end, &format!(" \0{role}\0 "));
    }
    let source = re!(r"[,;.]").replace_all(&source, " ");
    Some(
        re!(r"\s+")
            .replace_all(source.trim(), " ")
            .to_ascii_lowercase(),
    )
}

fn closed_supplied_day_shape(input: &str, spans: Vec<(usize, usize, &str)>) -> bool {
    let Some(source) = supplied_role_source(input, spans) else {
        return false;
    };
    let Some((prefix, after_rate)) = source.split_once(" \0r\0 ") else {
        return false;
    };
    if !re!(r"^((?:calculate|compute) simple interest (?:on|for) \x00p\x00 at|find (?:the )?simple interest (?:on|earned by) \x00p\x00 at|a principal of \x00p\x00 earns simple annual interest at|a \x00p\x00 principal (?:earns|accrues) simple interest at|for (?:a )?\x00p\x00(?: principal)? at|on principal \x00p\x00 calculate simple interest at)$")
        .is_match(prefix)
    {
        return false;
    }
    let Some(time) = re!(r"^(?:simple annual interest )?(?:(?:per year|per annum|yearly|annually) )?(?:\x00n\x00 )?(?:(?:use|using|under) (?:a |the )?\x00b\x00 (?:and|with|of) (?:exactly )?\x00d\x00|(?:over|for) \x00d\x00 (?:on|using) (?:a |the )?\x00b\x00) (.+)$")
        .captures(after_rate)
    else {
        return false;
    };
    let Some(after_fee) = re!(r"^(?:(?:(?:then|afterward) )?(?:apply|deduct|charge|subtract) (?:a |an )?(?:\x00f\x00(?: after-interest)? fee|after-interest fee of \x00f\x00|\x00f\x00)(?: after (?:interest|accrual)| afterward)?|a \x00f\x00 fee is charged after accrual) (.+)$")
        .captures(&time[1])
    else {
        return false;
    };
    let Some(permission) = after_fee[1].strip_suffix(" \0goals\0") else {
        return false;
    };
    re!(r"^(?:and )?(?:(?:allow|permit|allowing) (?:a |the resulting )?(?:negative (?:post-fee |ending )?(?:balance|balances|result|remainder)|balance to be below zero)|with negative post-fee balances allowed|negative post-fee balances are (?:explicitly )?(?:allowed|permitted)|do not allow a negative post-fee balance)(?: and)?$")
        .is_match(permission)
}

fn supplied_day_interest_roles(
    input: &str,
    context: &Context,
) -> Option<Result<SuppliedDayInterestRoles, Error>> {
    if !re!(r"(?i)\bsimple\s+(?:annual\s+)?interest\b").is_match(input)
        || !re!(r"(?i)\bfee\b|\bcharge\b").is_match(input)
        || !input.contains('%')
        || !re!(r"(?i)\bdays?\b").is_match(input)
    {
        return None;
    }
    Some((|| {
        let invalid = || Error("unsupported_financial_parameters".into());
        let money = super::money_records().find_iter(input).collect::<Vec<_>>();
        if money.len() != 2 {
            return Err(invalid());
        }
        let rates = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?(?:e[+-]?[0-9]+)?)%")
            .captures_iter(input)
            .collect::<Vec<_>>();
        if rates.len() != 1
            || money[0].start() >= rates[0].get(0).unwrap().start()
            || money[1].start() <= rates[0].get(0).unwrap().end()
        {
            return Err(invalid());
        }
        let basis = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?)\s*-\s*day\s+(?:basis|convention|year)\b|([0-9][0-9,]*(?:\.[0-9]+)?)\s+days\s+per\s+year\b")
            .captures_iter(input)
            .collect::<Vec<_>>();
        if basis.len() != 1 {
            return Err(invalid());
        }
        let basis_span = basis[0].get(0).unwrap();
        let basis = basis[0]
            .get(1)
            .or_else(|| basis[0].get(2))
            .unwrap()
            .as_str();
        let days = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?)\s+(?:(?:elapsed|total)\s+)?days\b")
            .captures_iter(input)
            .filter(|c| {
                let suffix = &input[c.get(0).unwrap().end()..];
                !re!(r"(?i)^\s+per\s+year\b").is_match(suffix)
            })
            .collect::<Vec<_>>();
        if days.len() != 1 {
            return Err(invalid());
        }
        let nominal = re!(r"(?i)\b(?:for|over)\s+([0-9][0-9,]*(?:\.[0-9]+)?)\s+(months?|years?)\b")
            .captures_iter(input)
            .collect::<Vec<_>>();
        if nominal.len() > 1 {
            return Err(invalid());
        }
        if let Some(nominal) = nominal.first() {
            let engine = super::super::compositions::Compositions::default();
            let nominal = financial_period(&nominal[1], false, &engine, context)?;
            let elapsed = financial_period(&days[0][1].replace(',', ""), false, &engine, context)?;
            if nominal.is_zero() != elapsed.is_zero() {
                return Err(Error("invalid_duration".into()));
            }
        }
        let fee_after = re!(r"(?i)\b(?:after\s+(?:interest|accrual)|afterward|after-interest|then\s+(?:subtract|deduct))\b")
            .is_match(input);
        if !fee_after || re!(r"(?i)\b(?:before\s+interest|fee\s+first)\b").is_match(input) {
            return Err(invalid());
        }
        let goal = re!(r"(?i)\b(?:return|report|provide|give|output|state)\b")
            .find_iter(input)
            .last()
            .ok_or_else(invalid)?;
        let goal_start = goal.start();
        let goal = &input[goal.end()..];
        if !re!(r"(?i)^\s*(?:the\s+)?interest\s*,?\s*(?:then|followed\s+by|and)\s+(?:(?:the|final|ending|remaining|post-fee)\s+)*(?:balance|amount|remainder)(?:\s+after\s+fee)?\s*$")
            .is_match(goal)
        {
            return Err(invalid());
        }
        let denied = re!(r"(?i)\b(?:do\s+not|don't|never|not)\s+(?:allow|permit)\b|\bnegative\b[^.;]*\bnot\s+(?:allowed|permitted)\b")
            .is_match(input);
        let signed = !denied
            && re!(r"(?i)\b(?:allow|allowed|allowing|permit|permitted)\b").is_match(input)
            && re!(r"(?i)\bnegative\b|\bbelow\s+zero\b").is_match(input);
        let mut spans = vec![
            (money[0].start(), money[0].end(), "p"),
            (money[1].start(), money[1].end(), "f"),
            (
                rates[0].get(0).unwrap().start(),
                rates[0].get(0).unwrap().end(),
                "r",
            ),
            (basis_span.start(), basis_span.end(), "b"),
            (
                days[0].get(0).unwrap().start(),
                days[0].get(0).unwrap().end(),
                "d",
            ),
            (goal_start, input.len(), "goals"),
        ];
        if let Some(nominal) = nominal.first() {
            let span = nominal.get(0).unwrap();
            spans.push((span.start(), span.end(), "n"));
        }
        if !closed_supplied_day_shape(input, spans) {
            return Err(invalid());
        }
        Ok(SuppliedDayInterestRoles {
            opening: money[0].as_str().to_owned(),
            fees: vec![(money[1].as_str().to_owned(), false)],
            rate: rates[0][1].to_owned(),
            elapsed_days: days[0][1].to_owned(),
            basis_days: basis.to_owned(),
            allow_negative: signed,
        })
    })())
}

/// Two authored fee stages straddle accrual; neither fee is inferred from a
/// total or silently folded into the interest-bearing principal.
fn supplied_two_fee_roles(input: &str) -> Option<Result<SuppliedDayInterestRoles, Error>> {
    if !re!(r"(?i)\bsimple\s+(?:annual\s+)?interest\b").is_match(input)
        || !re!(r"(?i)\bbefore\s+(?:accrual|interest)\b").is_match(input)
        || !re!(r"(?i)\bafter\s+(?:accrual|interest)\b").is_match(input)
    {
        return None;
    }
    Some((|| {
        let invalid = || Error("unsupported_financial_parameters".into());
        let money = super::money_records().find_iter(input).collect::<Vec<_>>();
        let rates = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?(?:e[+-]?[0-9]+)?)%")
            .captures_iter(input)
            .collect::<Vec<_>>();
        let days = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?)\s+(?:(?:elapsed|total)\s+)?days\b")
            .captures_iter(input)
            .collect::<Vec<_>>();
        let basis = re!(r"(?i)([0-9][0-9,]*(?:\.[0-9]+)?)\s*-\s*day\s+(?:basis|convention|year)\b|([0-9][0-9,]*(?:\.[0-9]+)?)\s+days\s+per\s+year\b")
            .captures_iter(input)
            .collect::<Vec<_>>();
        let goal = re!(r"(?i)\b(?:give|report|return|provide|output|state)\b")
            .find_iter(input)
            .last()
            .ok_or_else(invalid)?;
        if money.len() != 3 || rates.len() != 1 || days.len() != 1 || basis.len() != 1 {
            return Err(invalid());
        }
        let request = &input[goal.start()..];
        if !re!(r"(?i)^(?:give|report|return|provide|output|state)\s+(?:the\s+)?interest\s+(?:and|then)\s+(?:the\s+)?(?:signed\s+)?(?:final|ending)\s+balance$")
            .is_match(request)
        {
            return Err(invalid());
        }
        let rate = rates[0].get(0).unwrap();
        let day = days[0].get(0).unwrap();
        let basis_span = basis[0].get(0).unwrap();
        let spans = vec![
            (money[0].start(), money[0].end(), "p"),
            (rate.start(), rate.end(), "r"),
            (day.start(), day.end(), "d"),
            (basis_span.start(), basis_span.end(), "b"),
            (money[1].start(), money[1].end(), "f1"),
            (money[2].start(), money[2].end(), "f2"),
            (goal.start(), input.len(), "goals"),
        ];
        let source = supplied_role_source(input, spans).ok_or_else(invalid)?;
        if !re!(r"^for \x00p\x00 at \x00r\x00 simple annual interest (?:over|for) \x00d\x00 (?:on|using) (?:a |the )?\x00b\x00 (?:charge|subtract|deduct) \x00f1\x00 before (?:accrual|interest) and (?:another |then )?\x00f2\x00 after (?:accrual|interest) interest applies to the post-first-fee principal and \x00goals\x00$")
            .is_match(&source)
        {
            return Err(invalid());
        }
        Ok(SuppliedDayInterestRoles {
            opening: money[0].as_str().to_owned(),
            fees: vec![
                (money[1].as_str().to_owned(), true),
                (money[2].as_str().to_owned(), false),
            ],
            rate: rates[0][1].to_owned(),
            elapsed_days: days[0][1].to_owned(),
            basis_days: basis[0]
                .get(1)
                .or_else(|| basis[0].get(2))
                .unwrap()
                .as_str()
                .to_owned(),
            allow_negative: re!(r"(?i)\bsigned\s+(?:final|ending)\s+balance\b").is_match(request),
        })
    })())
}

pub(super) fn simple_interest_fee_report(input: &str, context: &Context) -> Outcome {
    let input = input.trim().trim_end_matches(['.', '?']);
    let fee_first = re!(r"(?i)^beginning with (.+?), subtract a (.+?) fee and then calculate (.+?)% simple interest for (.+?) days on the post-fee amount using a (.+?)-day year; report interest and closing balance to cents, half up$")
        .captures(input)
        .map(|c| (c[1].to_owned(), c[2].to_owned(), c[3].to_owned(), c[4].to_owned(), c[5].to_owned(), true, false, "days"));
    let signed = re!(r"(?i)^for a (.+?) principal with a (.+?) fee charged first, then (.+?)% simple annual interest for (.+?) days on the resulting balance using a (.+?)-day year, give interest and ending amount rounded half up to cents, including any negative amount$")
        .captures(input)
        .map(|c| (c[1].to_owned(), c[2].to_owned(), c[3].to_owned(), c[4].to_owned(), c[5].to_owned(), true, true, "days"));
    let interest_first = re!(r"(?i)^for a (.+?) balance, add (.+?)% simple interest for (.+?) days using a (.+?)-day year, then deduct a (.+?) fee; report the interest and final balance to cents with half-up rounding$")
        .captures(input)
        .map(|c| (c[1].to_owned(), c[5].to_owned(), c[2].to_owned(), c[3].to_owned(), c[4].to_owned(), false, false, "days"));
    let monthly_interest_first = re!(r"(?i)^a (.+?) balance earns (.+?)% simple annual interest for (.+?) months; first compute and add interest, then subtract a (.+?) fee\. give interest and ending balance to the nearest cent, rounding half up$")
        .captures(input)
        .map(|c| (c[1].to_owned(), c[4].to_owned(), c[2].to_owned(), c[3].to_owned(), "12".to_owned(), false, false, "months"));
    let roles = fee_first
        .or(signed)
        .or(interest_first)
        .or(monthly_interest_first);
    let (opening, fees, rate, days, year_days, allow_negative, period_unit) = match roles {
        Some((opening, fee, rate, days, year_days, fee_before, allow_negative, unit)) => (
            opening,
            vec![(fee, fee_before)],
            rate,
            days,
            year_days,
            allow_negative,
            unit,
        ),
        None => match supplied_two_fee_roles(input)
            .or_else(|| supplied_day_interest_roles(input, context))?
        {
            Ok(roles) => (
                roles.opening,
                roles.fees,
                roles.rate,
                roles.elapsed_days,
                roles.basis_days,
                roles.allow_negative,
                "days",
            ),
            Err(error) => return Some(Err(error)),
        },
    };
    Some((|| {
        if input.len() > 4096 {
            return Err(Error("expression_too_complex".into()));
        }
        let bounded = super::super::model_coordinates::bounded;
        let engine = super::super::compositions::Compositions::default();
        let (opening, code) = super::nonnegative_money_coordinate(&opening, &engine, context)?;
        let mut before = BigRational::zero();
        let mut after = BigRational::zero();
        for (fee_input, fee_before) in fees {
            let (fee, fee_code) =
                super::nonnegative_money_coordinate(&fee_input, &engine, context)?;
            let normalized_fee = super::normalize_grouped_money(&fee_input)
                .ok_or_else(|| Error("invalid_financial_argument".into()))?;
            engine.quantity_value(&normalized_fee, code, context)?;
            let fee = super::money_in_currency(fee.value, fee_code, code, context)?;
            if fee_before {
                before = bounded(before + fee)?;
            } else {
                after = bounded(after + fee)?;
            }
        }
        let rate = super::super::model_coordinates::read(&rate, "1", &engine, context)?.value;
        let days = super::super::model_coordinates::read(
            &format!("{days} {period_unit}"),
            period_unit,
            &engine,
            context,
        )?
        .value;
        let year_days = super::super::model_coordinates::read(
            &format!("{year_days} {period_unit}"),
            period_unit,
            &engine,
            context,
        )?
        .value;
        if rate.is_negative() {
            return Err(Error("invalid_financial_rate".into()));
        }
        if days.is_negative() || !year_days.is_positive() {
            return Err(Error("invalid_duration".into()));
        }
        let principal = bounded(&opening.value - before)?;
        if principal.is_negative() && !allow_negative {
            return Err(Error("invalid_financial_argument".into()));
        }
        let interest = bounded(
            &principal * rate * days / bounded(BigRational::from_integer(100.into()) * year_days)?,
        )?;
        let ending = bounded(principal + &interest - after)?;
        if ending.is_negative() && !allow_negative {
            return Err(Error("invalid_financial_argument".into()));
        }
        // Round only the two requested terminal fields. The exact interest
        // above is still used when calculating the exact ending balance.
        let interest = super::round_money_to_cents(&interest)?;
        let ending = super::round_money_to_cents(&ending)?;
        let money = |amount: &BigRational| {
            format!("(rational({},{}) {code})", amount.numer(), amount.denom())
        };
        let interest = money(&interest);
        let ending = money(&ending);
        engine.evaluate_money(&interest, context)?;
        engine.evaluate_money(&ending, context)?;
        Ok(format!(
            "finance_annual_report(interest earned|{interest};ending balance|{ending})"
        ))
    })())
}

fn balance_targets() -> &'static regex::Regex {
    re!(
        r"(?i)\b((?:resulting|ending|final) balance) (?:in|to|into) ([^,;.?]+?)(\s+and\s+|\s+using\s+|[,;.?]|$)"
    )
}

pub(super) fn balance_interest_goals(input: &str) -> Result<Option<[super::Goal; 2]>, Error> {
    let input = input.trim().trim_end_matches(['.', '?']);
    // Yield/loss requests can precede the last clause; their existing owner
    // collects every requested role across the complete input.
    if report_goal(input)?.is_some() {
        return Ok(None);
    }
    let Some((_, request)) = super::super::syntax::split_last(input, &[";", ". "]) else {
        return Ok(None);
    };
    // A no-transactions statement is a model constraint before the goals,
    // rather than a requested scalar result. Leave every other clause intact
    // so the complete paired-goal parser can reject unsupported additions.
    let request = re!(r"(?i)^assume no (?:other )?transactions and ")
        .replace(request.trim_start(), "")
        .into_owned();
    let request = balance_targets().replace_all(&request, "$1$3");
    let request = if let Some(c) =
        re!(r"(?i)^using nominal annual rate divided by (.+?), (.+), to cents$")
            .captures(request.trim())
    {
        let (n, d) = super::super::integer_queries::ratio_value(&c[1])?;
        let divisor = BigRational::new(n, d);
        let frequencies = re!(
            r"(?i)\bcompound(?:ed|ing|s)? (annually|yearly|monthly|quarterly|semiannually|weekly)\b"
        )
        .captures_iter(input)
        .collect::<Vec<_>>();
        if frequencies.len() != 1
            || divisor
                != BigRational::from_integer(BigInt::from(
                    super::frequency(&frequencies[0][1].to_ascii_lowercase()).unwrap() as u64,
                ))
        {
            return Err(Error("invalid_financial_rate".into()));
        }
        c[2].to_string()
    } else {
        request.into_owned()
    };
    // A paired money report must consume its complete goal clause, including
    // any extra roles.
    if !re!(r"(?i)^\s*(?:calculate|compute|give|return|find|report|what (?:are|is))\b")
        .is_match(&request)
        || !re!(r"(?i)\b(?:ending|final|resulting) balance\b").is_match(&request)
        || !re!(r"(?i)\b(?:interest (?:earned|accrued)|total interest)\b").is_match(&request)
    {
        return Ok(None);
    }
    let c = re!(r"(?i)^\s*(?:calculate|compute|give|return|find|report|what (?:are|is)) (?:the )?((?:ending|final|resulting) balance|interest (?:earned|accrued)|total interest(?: (?:earned|accrued))?)(?: to cents)? and (?:the )?((?:ending|final|resulting) balance|interest (?:earned|accrued)|total interest(?: (?:earned|accrued))?)(?: to cents)?\s*$")
        .captures(&request)
        .ok_or_else(|| Error("unsupported_financial_parameters".into()))?;
    let goal = |role: &str| {
        if role.to_ascii_lowercase().contains("interest") {
            super::Goal::Interest
        } else {
            super::Goal::Balance
        }
    };
    let first = goal(&c[1]);
    let second = goal(&c[2]);
    Ok(matches!(
        (first, second),
        (super::Goal::Balance, super::Goal::Interest)
            | (super::Goal::Interest, super::Goal::Balance)
    )
    .then_some([first, second]))
}

pub(super) fn report_goal(input: &str) -> Result<Option<ReportGoal>, Error> {
    let without_target = balance_targets().replace_all(input, "$1$3");
    let goals = re!(
        r"(?i)\b(?:calculate|compute|give|return|find|report|what (?:are|is))\s+((?:(?:the|its|percentage|cumulative|effective|period|total|ending|final|and|balance|yield|loss|interest|earned|accrued)\b\s*)+)"
    );
    let mut balance = balance_targets().is_match(input);
    let mut interest = false;
    let mut loss = false;
    let mut yield_requested = false;
    let mut incomplete_role = false;
    for c in goals.captures_iter(&without_target) {
        let goal = c[1].to_ascii_lowercase();
        incomplete_role |= goal.trim_end().ends_with("and");
        balance |= goal.contains("balance");
        interest |= goal.contains("interest");
        loss |= goal.contains("loss");
        yield_requested |= re!(r"\b(?:yield|loss)\b").is_match(&goal);
    }
    if yield_requested && incomplete_role {
        return Err(Error("unsupported_financial_parameters".into()));
    }
    Ok(yield_requested.then_some(ReportGoal {
        balance,
        interest,
        loss,
    }))
}

fn target_currency(input: &str, paired_goals: bool) -> Result<Option<&'static str>, Error> {
    let mut target = None;
    let goal_start = if paired_goals {
        super::super::syntax::split_last(input, &[";", ". "])
            .map(|(_, request)| input.len() - request.len())
    } else {
        None
    };
    for c in balance_targets().captures_iter(input) {
        // The paired-goal reader has already consumed this exact precision
        // qualifier. It is not an output currency.
        if goal_start.is_some_and(|start| c.get(0).unwrap().start() >= start)
            && c[2].trim().eq_ignore_ascii_case("cents")
        {
            continue;
        }
        let currency = super::super::finance::currency(c[2].trim())
            .ok_or_else(|| Error("incompatible_units".into()))?;
        if target.is_some_and(|old| old != currency) {
            return Err(Error("unsupported_financial_parameters".into()));
        }
        target = Some(currency);
    }
    Ok(target)
}

pub(super) fn paired_report_target(input: &str) -> Result<Option<&'static str>, Error> {
    target_currency(input, true)
}

pub(super) fn report_target(input: &str) -> Result<Option<&'static str>, Error> {
    target_currency(input, false)
}

pub(super) fn validate_currency_records(input: &str, context: &Context) -> Result<(), Error> {
    let records =
        re!(r"(?i)\busing ([a-z]{3})\s*=\s*(.+?) and ([a-z]{3})\s*=\s*(.+?) per common base\b");
    let engine = super::super::compositions::Compositions::default();
    for c in records.captures_iter(input) {
        for (code, value) in [(&c[1], &c[2]), (&c[3], &c[4])] {
            super::super::finance::validate_supplied_rate(code, value, &engine, context)?;
        }
    }
    if re!(r"(?i)\b(?:using\b.*)?[a-z]{3}\s*=").is_match(&records.replace_all(input, "")) {
        return Err(Error("invalid_financial_rate".into()));
    }
    Ok(())
}

pub(super) fn has_definitions(input: &str) -> bool {
    re!(r"(?i)\b(?:monthly|quarterly|semiannual(?:ly)?|weekly|annual|periodic)\s+(?:interest\s+)?(?:rate|factor)\s*(?:is|of|=)|\buse\s+(?:a\s+)?factor\b").is_match(input)
}

pub(super) fn prepare(input: &str) -> Result<(String, Vec<Definition>), Error> {
    // Normalize the two supplied-record orders, retaining the entire expression.
    let input =
        re!(r"(?i)\buse factor ([0-9eE.()+*/^ \t-]*[0-9)]) (monthly|quarterly|weekly|annually)\b")
            .replace_all(input, "$2 factor = $1");
    let calls = re!(
        r"(?i)\b(?:use\s+(?:a\s+)?)?(monthly|quarterly|semiannual(?:ly)?|weekly|annual|periodic)\s+(?:interest\s+)?(rate|factor)\s*(?:is|of|=)\s*([0-9eE.()+*/^ \t-]*[0-9)])\s*(%)?"
    );
    let mut definitions = Vec::new();
    let mut output = String::new();
    let mut start = 0;
    let primary_percentage = input.find('%');
    for c in calls.captures_iter(&input) {
        let span = c.get(0).unwrap();
        let after = input[span.end()..].trim_start();
        if after.starts_with(['+', '-', '*', '/', '^', ')']) {
            return Err(Error("invalid_financial_rate".into()));
        }
        if !after.is_empty() && !after.starts_with(['.', ',', ';', '?', '!']) {
            let word = after
                .split_whitespace()
                .next()
                .unwrap()
                .to_ascii_lowercase();
            if !matches!(
                word.as_str(),
                "compound"
                    | "compounds"
                    | "compounded"
                    | "compounding"
                    | "per"
                    | "a"
                    | "every"
                    | "each"
                    | "monthly"
                    | "quarterly"
                    | "weekly"
                    | "annual"
                    | "annually"
                    | "yearly"
                    | "nominal"
                    | "effective"
                    | "interest"
                    | "for"
                    | "after"
                    | "over"
                    | "on"
                    | "and"
                    | "with"
                    | "give"
                    | "find"
                    | "calculate"
                    | "compute"
                    | "return"
                    | "what"
            ) {
                return Err(Error("invalid_financial_rate".into()));
            }
        }
        // A named rate can be the primary percentage, rather than a redundant record.
        if c.get(4)
            .is_some_and(|percent| Some(percent.start()) == primary_percentage)
        {
            continue;
        }
        let (n, d) = super::super::integer_queries::ratio_value(c[3].trim())?;
        if n.bits().max(d.bits()) > 4096 || definitions.len() >= 8 {
            return Err(Error("integer_limit".into()));
        }
        let mut value = BigRational::new(n, d);
        if c.get(4).is_some() {
            value /= BigInt::from(100);
        }
        if c[2].eq_ignore_ascii_case("factor") {
            if c.get(4).is_some() {
                return Err(Error("invalid_financial_rate".into()));
            }
            value -= BigRational::one();
        }
        let basis = if c[1].eq_ignore_ascii_case("periodic") {
            None
        } else {
            super::frequency(&c[1].to_ascii_lowercase())
        };
        definitions.push(Definition { basis, value });
        output.push_str(&input[start..span.start()]);
        start = span.end();
    }
    output.push_str(&input[start..]);
    if has_definitions(&calls.replace_all(&input, "")) {
        return Err(Error("invalid_financial_rate".into()));
    }
    Ok((output, definitions))
}

pub(super) fn validate(
    primary: &str,
    rate_basis: f64,
    frequency: f64,
    effective: bool,
    negative: bool,
    definitions: &[Definition],
) -> Result<(), Error> {
    if definitions.is_empty() {
        return Ok(());
    }
    let (n, d) = super::super::integer_queries::ratio_value(primary)?;
    let mut annual = BigRational::new(n, d * 100);
    if negative {
        annual = -annual.abs();
    }
    annual *= BigInt::from(rate_basis as i32);
    for definition in definitions {
        let basis = definition.basis.unwrap_or(frequency) as i32;
        if effective {
            let factor = BigRational::one() + &definition.value;
            if factor < BigRational::zero()
                || factor.numer().bits().max(factor.denom().bits()) * basis as u64 > 65_536
            {
                return Err(Error("invalid_financial_rate".into()));
            }
            if factor.pow(basis) != BigRational::one() + &annual {
                return Err(Error("invalid_financial_rate".into()));
            }
        } else if &definition.value * BigInt::from(basis) != annual {
            return Err(Error("invalid_financial_rate".into()));
        }
    }
    Ok(())
}

pub(super) fn primary_basis(prefix: &str, tail: &str) -> Option<f64> {
    let noun = re!(
        r"(?i)^\s*(?:interest\s+)?(?:per|a|every|each)\s+(month|quarter|week|half[ -]year|year)\b"
    );
    if let Some(c) = noun.captures(tail) {
        return Some(match &c[1].to_ascii_lowercase()[..] {
            "month" => 12.0,
            "quarter" => 4.0,
            "week" => 52.0,
            "half year" | "half-year" => 2.0,
            _ => 1.0,
        });
    }
    let before = re!(
        r"(?i)\b(monthly|quarterly|weekly|semiannual(?:ly)?|annual|annually|yearly)(?:\s+(?:interest|growth))?\s+rate\s*(?:of|at|is|=)?\s*$"
    );
    let after = re!(
        r"(?i)^\s*(?:interest\s+)?(?:(?:nominal|effective)\s+)?(monthly|quarterly|weekly|semiannual(?:ly)?|annual|annually|yearly)\b"
    );
    before
        .captures(prefix)
        .or_else(|| after.captures(tail))
        .and_then(|c| super::frequency(&c[1].to_ascii_lowercase()))
        .or_else(|| {
            re!(r"(?i)\bapy\s*(?:of|at|is|=)?\s*$")
                .is_match(prefix)
                .then_some(1.0)
        })
}