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
//! Explicit scalar mechanics questions lower to the ordinary typed evaluator.
//! Signs describe components along a chosen axis; no gravity or material constants are implicit.
mod supplied_reports;

use super::compositions::Compositions;
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};

fn encode_support(name: &str) -> String {
    name.as_bytes()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect::<Vec<_>>()
        .join("")
}

fn decode_support(encoded: &str) -> Result<String, Error> {
    if encoded.is_empty() || !encoded.is_ascii() || !encoded.len().is_multiple_of(2) {
        return Err(Error("invalid_expression".into()));
    }
    let bytes = encoded
        .as_bytes()
        .as_chunks::<2>()
        .0
        .iter()
        .map(|pair| {
            let pair = std::str::from_utf8(pair).map_err(|_| Error("invalid_expression".into()))?;
            u8::from_str_radix(pair, 16).map_err(|_| Error("invalid_expression".into()))
        })
        .collect::<Result<Vec<_>, _>>()?;
    let name = String::from_utf8(bytes).map_err(|_| Error("invalid_expression".into()))?;
    if !re!(r"^[A-Za-z][A-Za-z0-9_]*$").is_match(&name) {
        return Err(Error("invalid_expression".into()));
    }
    Ok(name)
}

fn typed_coordinate(
    coordinate: &super::model_coordinates::Coordinate,
    unit: &str,
) -> Result<String, Error> {
    let scalar = if coordinate.authored {
        format!(
            "rational({},{})",
            coordinate.value.numer(),
            coordinate.value.denom()
        )
    } else {
        let value = coordinate
            .value
            .to_f64()
            .filter(|value| value.is_finite())
            .ok_or_else(|| Error("numeric_overflow".into()))?;
        if value == 0.0 && !coordinate.value.is_zero() {
            return Err(Error("numeric_underflow".into()));
        }
        format!("real({value:e})")
    };
    Ok(if unit == "1" {
        scalar
    } else {
        format!("({scalar} {unit})")
    })
}

/// The complete rotating-energy formula owner selects explicit physical roles.
/// Angular units remain dimensional everywhere outside that supplied model.
pub(super) fn supplied_formula_role(
    role: &str,
    value: &str,
    engine: &Compositions,
    context: &Context,
) -> Result<String, Error> {
    if value.len() > 4096 {
        return Err(Error("expression_too_complex".into()));
    }
    let angular = match role.trim().to_ascii_lowercase().as_str() {
        "moment of inertia" => false,
        "angular speed" => true,
        _ => return Err(Error("invalid_expression".into())),
    };
    let reference = if angular { "rad/s" } else { "kg*m²" };
    let normalized = formula_role_units(value, engine, context);
    let magnitude = engine.quantity_value(&normalized, reference, context)?;
    if magnitude < 0.0 {
        return Err(Error("invalid_physical_quantity".into()));
    }
    Ok(if angular {
        // Use its original converted quantity, not a rounded scalar coordinate.
        format!("(({normalized}) / (1 rad))")
    } else {
        format!("({normalized})")
    })
}

fn formula_role_units(input: &str, engine: &Compositions, context: &Context) -> String {
    for (index, _) in input.char_indices().skip(1) {
        let suffix = input[index..].trim();
        let units = super::compound_units::explicit_products(suffix, |leaf| {
            engine.units.unit(leaf).is_some()
        });
        if units == suffix
            || super::compound_units::factors(&units, |leaf| engine.units.unit(leaf).is_some())
                .is_none()
        {
            continue;
        }
        let coefficient = input[..index].trim();
        if engine.quantity_value(coefficient, "1", context).is_ok() {
            return format!("({coefficient}) {units}");
        }
    }
    input.to_string()
}

#[derive(Default)]
pub struct Mechanics {
    compositions: Compositions,
}

impl Plugin for Mechanics {
    fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
        self.lower(input, context).transpose()
    }
    fn rewrite(&self, input: &str, context: &Context) -> Outcome {
        super::syntax::rewrite_groups(input, |part| self.lower(part, context).transpose())
    }
    fn evaluate(&self, input: &str, context: &Context) -> Outcome {
        let input = super::syntax::ungroup(input);
        if let Some(inner) = input
            .strip_prefix("mechanics_support_report(")
            .and_then(|value| value.strip_suffix(')'))
        {
            return Some((|| {
                if input.len() > 4096 {
                    return Err(Error("invalid_expression".into()));
                }
                let fields = inner.split(';').collect::<Vec<_>>();
                let [first, second, load, ratio] = fields.as_slice() else {
                    return Err(Error("invalid_expression".into()));
                };
                let first = decode_support(first)?;
                let second = decode_support(second)?;
                if first.eq_ignore_ascii_case(&second) {
                    return Err(Error("invalid_expression".into()));
                }
                let read = |expression: &str, unit: &str| {
                    super::model_coordinates::read(expression, unit, &self.compositions, context)
                };
                let load = read(load, "N")?;
                let ratio = read(ratio, "1")?;
                if load.value.is_negative() || ratio.value.is_negative() {
                    return Err(Error("invalid_physical_quantity".into()));
                }
                let bounded = super::model_coordinates::bounded;
                let second_value =
                    bounded(&load.value / (&ratio.value + BigRational::from_integer(1.into())))?;
                let first_value = bounded(&ratio.value * &second_value)?;
                if bounded(&first_value + &second_value)? != load.value {
                    return Err(Error("invalid_expression".into()));
                }
                let display = |value: BigRational| {
                    let coordinate = super::model_coordinates::Coordinate {
                        value,
                        authored: load.authored && ratio.authored,
                    };
                    let expression = typed_coordinate(&coordinate, "N")?;
                    self.compositions
                        .evaluate(&format!("({expression}) in N"), context)
                        .ok_or_else(|| Error("invalid_expression".into()))?
                };
                Ok(format!(
                    "reaction {first}: {}; reaction {second}: {}; balanced: true",
                    display(first_value)?,
                    display(second_value)?
                ))
            })());
        }
        let inner = input
            .strip_prefix("mechanics_summary(")?
            .strip_suffix(')')?;
        Some((|| {
            if input.len() > 4096 {
                return Err(Error("invalid_expression".into()));
            }
            let fields = inner.split(';').collect::<Vec<_>>();
            let cart = fields.len() == 4
                && fields.iter().map(|field| field.split('|').next()).eq([
                    Some("acceleration"),
                    Some("final speed"),
                    Some("displacement"),
                    Some("final kinetic energy"),
                ]);
            if !(2..=3).contains(&fields.len()) && !cart {
                return Err(Error("invalid_expression".into()));
            }
            let mut output = Vec::new();
            for field in fields {
                let parts = field.split('|').collect::<Vec<_>>();
                if parts.len() != 3 {
                    return Err(Error("invalid_expression".into()));
                }
                let (label, target, expression) = (parts[0], parts[1], parts[2]);
                self.validate_report_field(label, target, expression, context)?;
                let display = self
                    .compositions
                    .evaluate(&format!("({expression}) in {target}"), context)
                    .ok_or_else(|| Error("invalid_expression".into()))??;
                output.push(format!("{label}: {display}"));
            }
            Ok(output.join("; "))
        })())
    }
}

#[derive(Clone, Copy)]
enum Domain {
    Signed,
    Nonnegative,
    Positive,
}

impl Mechanics {
    fn lower(&self, input: &str, context: &Context) -> Result<Option<String>, Error> {
        let trimmed = input.trim().trim_end_matches(['.', '?']);
        if let Some(result) = self.supplied_reports(trimmed, context)? {
            return Ok(Some(result));
        }
        if let Some(c) = re!(r"(?i)^add a mass of (.+?) to a duration of (.+?), then express the total in SI base units$").captures(trimmed) {
            self.compositions.quantity_value(&c[1], "kg", context)?;
            self.compositions.quantity_value(&c[2], "seconds", context)?;
            let expression = format!("({}) + ({})", &c[1], &c[2]);
            // Shared typed addition owns dimension errors before presentation.
            self.compositions.quantity_value(&expression, "kg", context)?;
            return Ok(Some(format!("({expression}) in kg")));
        }
        // Do not scan normal arithmetic or unrelated language for physical measurements.
        if !re!(r"(?i)\b(momentum|kinetic|potential|accelera\w*|decelera\w*|brakes|slows|displacement|net force|work|power|u\s*=)\b").is_match(input) {
            return Ok(None);
        }
        let input = input.replace('−', "-");
        let input = input.trim().trim_end_matches(['.', '?']);
        let (mut shape, quantities) = self.measurements(input);
        let mut target = None;
        if let Some((sentence, unit)) = shape.rsplit_once(" in ")
            && self.unit(unit)
        {
            target = Some(unit.to_string());
            shape = sentence.into();
        }
        let shape = shape.as_str();
        macro_rules! q {
            ($c:ident, $index:literal, $unit:literal, $domain:ident) => {
                self.role(&$c[$index], &quantities, $unit, Domain::$domain, context)?
            };
        }
        macro_rules! rule {
            ($pattern:literal, $default:literal, $c:ident, $expression:expr) => {
                if let Some($c) = re!($pattern).captures(shape) {
                    let expression = $expression;
                    return Ok(Some(format!(
                        "({expression}) in {}",
                        target.as_deref().unwrap_or($default)
                    )));
                }
            };
        }

        if let Some(c) = re!(r"(?i)^a @(\d+) [a-z '-]+ accelerates at @(\d+); (?:find|calculate|determine) the net force and the work done over @(\d+) in the force direction$").captures(shape) {
            let m = q!(c, 1, "kg", Positive);
            let a = q!(c, 2, "m/s²", Signed);
            let distance = q!(c, 3, "m", Nonnegative);
            let force = format!("{m} * {a}");
            return self.report(&[("net force", "N", force.clone()),
                ("work", "J", format!("abs({force}) * {distance}"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a @(\d+) [a-z '-]+ moving at @(\d+) brakes uniformly to rest over @(\d+); (?:determine|find|calculate) its acceleration and stopping time$").captures(shape) {
            // Mass is supplied evidence even though it cancels from kinematics.
            let _mass = q!(c, 1, "kg", Positive);
            let speed = q!(c, 2, "m/s", Positive);
            let distance = q!(c, 3, "m", Positive);
            return self.report(&[("acceleration", "m/s²", format!("-square({speed}) / (2 * {distance})")),
                ("stopping time", "s", format!("2 * {distance} / {speed}"))], context).map(Some);
        }

        if let Some(c) = re!(r"(?i)^a @(\d+) [a-z '-]+ accelerates at @(\d+) for @(\d+) from rest; report force, final speed, and distance (?:traveled|travelled)$").captures(shape) {
            let mass = q!(c, 1, "kg", Positive);
            let acceleration = q!(c, 2, "m/s²", Signed);
            let time = q!(c, 3, "seconds", Nonnegative);
            return self.report(&[("force", "N", format!("{mass} * {acceleration}")),
                ("final speed", "m/s", format!("abs({acceleration} * {time})")),
                ("distance", "m", format!("abs({acceleration}) * square({time}) / 2"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a @(\d+) [a-z '-]+ slows uniformly from @(\d+) to @(\d+) over @(\d+); (?:calculate|find) acceleration and elapsed time$").captures(shape) {
            let _mass = q!(c, 1, "kg", Positive);
            let initial = q!(c, 2, "m/s", Positive);
            let final_speed = q!(c, 3, "m/s", Nonnegative);
            let distance = q!(c, 4, "m", Positive);
            // "Slows" requires a genuine reduction; this inverse model does not
            // admit a constant-speed or increasing-speed interpretation.
            let u = super::model_coordinates::read(&initial, "m/s", &self.compositions, context)?;
            let v = super::model_coordinates::read(&final_speed, "m/s", &self.compositions, context)?;
            let s = super::model_coordinates::read(&distance, "m", &self.compositions, context)?;
            let authored = u.authored && v.authored && s.authored;
            let (u, v, s) = (u.value, v.value, s.value);
            if v >= u {
                return Err(Error("invalid_physical_value".into()));
            }
            // Preserve authored small speed differences before the typed boundary;
            // factoring also avoids subtracting two rounded velocity squares.
            let two = BigRational::from_integer(2.into());
            let acceleration = super::model_coordinates::bounded((&v - &u) * (&v + &u) / (&two * &s))?;
            let time = super::model_coordinates::bounded(two * s / (u + v))?;
            let emit = |value: &BigRational, unit: &str| -> Result<String, Error> {
                let scalar = if authored {
                    format!("rational({},{})", value.numer(), value.denom())
                } else {
                    let number = value.to_f64().filter(|value| value.is_finite())
                        .ok_or_else(|| Error("numeric_overflow".into()))?;
                    if number == 0.0 && !value.is_zero() {
                        return Err(Error("numeric_underflow".into()));
                    }
                    format!("real({number:e})")
                };
                Ok(format!("(({scalar}) {unit})"))
            };
            return self.report(&[("acceleration", "m/s²", emit(&acceleration, "m/s²")?),
                ("elapsed time", "seconds", emit(&time, "seconds")?)], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^an? @(\d+) [a-z '-]+ is raised @(\d+) in @(\d+); using g\s*=\s*@(\d+), (?:calculate|find) potential-energy change and average power$").captures(shape) {
            let mass = q!(c, 1, "kg", Positive);
            let height = q!(c, 2, "m", Nonnegative);
            let time = q!(c, 3, "seconds", Positive);
            let gravity = q!(c, 4, "m/s²", Positive);
            let energy = format!("{mass} * {gravity} * {height}");
            return self.report(&[("potential-energy change", "J", energy.clone()),
                ("average power", "W", format!("({energy}) / {time}"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a @(\d+) force acts at @(\d+) to a @(\d+) displacement; (?:calculate|find) work, using the angle measured between force and displacement$").captures(shape) {
            let force = q!(c, 1, "N", Nonnegative);
            let angle = q!(c, 2, "degrees", Nonnegative);
            let displacement = q!(c, 3, "m", Nonnegative);
            let coordinate = super::model_coordinates::read(&angle, "degrees", &self.compositions, context)?;
            if coordinate.value > BigRational::from_integer(180.into()) {
                return Err(Error("invalid_physical_value".into()));
            }
            // Authored cardinal directions have exact cosine identities. Other
            // angles use the existing scalar trig kernel at its typed boundary.
            let cosine = if coordinate.authored && coordinate.value == BigRational::from_integer(0.into()) {
                1.0
            } else if coordinate.authored && coordinate.value == BigRational::from_integer(90.into()) {
                0.0
            } else if coordinate.authored && coordinate.value == BigRational::from_integer(180.into()) {
                -1.0
            } else {
                let radians = self.compositions.quantity_value(&angle, "radians", context)?;
                super::arithmetic::eval(&format!("cos({radians:e})"))
                    .filter(|value| value.is_finite())
                    .ok_or_else(|| Error("invalid_physical_value".into()))?
            };
            return Ok(Some(format!("({force} * {displacement} * real({cosine:e})) in J")));
        }

        // Constant acceleration: v=u+at and s=ut+at²/2.
        rule!(
            r"(?i)^a [a-z '-]+ starts from rest and accelerates at @(\d+) for @(\d+); (?:find|calculate) its final (?:speed|velocity)$",
            "m/s",
            c,
            magnitude_if_speed(
                format!(
                    "{} * {}",
                    q!(c, 1, "m/s²", Signed),
                    q!(c, 2, "s", Nonnegative)
                ),
                shape
            )
        );
        rule!(
            r"(?i)^a [a-z '-]+ (?:travels|moves) at @(\d+) and accelerates at @(\d+) for @(\d+); (?:find|calculate) its (?:displacement|final speed|final velocity)$",
            "m",
            c,
            {
                let u = q!(c, 1, "m/s", Signed);
                let a = q!(c, 2, "m/s²", Signed);
                let t = q!(c, 3, "s", Nonnegative);
                // The selected output is a role, rather than inferred from its target unit.
                if shape.to_ascii_lowercase().ends_with("displacement") {
                    format!("{u} * {t} + 0.5 * {a} * square({t})")
                } else {
                    return Ok(Some(format!(
                        "({}) in {}",
                        magnitude_if_speed(format!("{u} + {a} * {t}"), shape),
                        target.as_deref().unwrap_or("m/s")
                    )));
                }
            }
        );
        rule!(
            r"(?i)^how far does a [a-z '-]+ travel in @(\d+) from an initial (?:speed|velocity) of @(\d+) with acceleration @(\d+)$",
            "m",
            c,
            {
                let t = q!(c, 1, "s", Nonnegative);
                format!(
                    "{} * {t} + 0.5 * {} * square({t})",
                    q!(c, 2, "m/s", Signed),
                    q!(c, 3, "m/s²", Signed)
                )
            }
        );
        rule!(
            r"(?i)^for u = @(\d+), a = @(\d+), and t = @(\d+), (?:calculate|find) the displacement$",
            "m",
            c,
            {
                let t = q!(c, 3, "s", Nonnegative);
                format!(
                    "{} * {t} + 0.5 * {} * square({t})",
                    q!(c, 1, "m/s", Signed),
                    q!(c, 2, "m/s²", Signed)
                )
            }
        );
        rule!(
            r"(?i)^a [a-z '-]+ has initial velocity @(\d+) and acceleration @(\d+) for @(\d+); (?:what is|find) its final velocity$",
            "m/s",
            c,
            format!(
                "{} + {} * {}",
                q!(c, 1, "m/s", Signed),
                q!(c, 2, "m/s²", Signed),
                q!(c, 3, "s", Nonnegative)
            )
        );
        rule!(
            r"(?i)^a [a-z '-]+ (?:slows|accelerates uniformly|slows uniformly) from @(\d+) to @(\d+) in @(\d+); (?:find|calculate) its (?:constant )?acceleration$",
            "m/s²",
            c,
            format!(
                "({} - {}) / {}",
                q!(c, 2, "m/s", Signed),
                q!(c, 1, "m/s", Signed),
                q!(c, 3, "s", Positive)
            )
        );
        rule!(
            r"(?i)^a[n]? [a-z '-]+ (?:accelerates|slows) uniformly from @(\d+) to @(\d+) over @(\d+); (?:find|calculate) (?:its|the) acceleration$",
            "m/s²",
            c,
            format!(
                "(square({}) - square({})) / (2 * {})",
                q!(c, 2, "m/s", Signed),
                q!(c, 1, "m/s", Signed),
                q!(c, 3, "m", Positive)
            )
        );
        rule!(
            r"(?i)^a [a-z '-]+ moving at @(\d+) brakes uniformly at @(\d+); how long until stopping$",
            "s",
            c,
            format!(
                "{} / {}",
                q!(c, 1, "m/s", Nonnegative),
                q!(c, 2, "m/s²", Positive)
            )
        );

        // Momentum and kinetic energy share measured mass and velocity roles.
        rule!(
            r"(?i)^a[n]? @(\d+) [a-z '-]+ (?:moves|travels|is launched|walks) at @(\d+); (?:find|calculate|determine|express|give|what is) (?:its|their|the [a-z '-]+) (?:signed )?momentum(?: along the chosen axis)?$",
            "kg·m/s",
            c,
            format!(
                "{} * {}",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 2, "m/s", Signed)
            )
        );
        rule!(
            r"(?i)^what speed does a @(\d+) [a-z '-]+ need to have momentum @(\d+)$",
            "m/s",
            c,
            format!(
                "abs({} / {})",
                q!(c, 2, "kg·m/s", Signed),
                q!(c, 1, "kg", Positive)
            )
        );
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ has momentum @(\d+); (?:find|determine) its (?:speed|velocity)$",
            "m/s",
            c,
            magnitude_if_speed(
                format!(
                    "{} / {}",
                    q!(c, 2, "kg·m/s", Signed),
                    q!(c, 1, "kg", Positive)
                ),
                shape
            )
        );
        rule!(
            r"(?i)^what is the mass of a[n]? [a-z '-]+ moving at @(\d+) with momentum @(\d+)$",
            "kg",
            c,
            self.mass(
                format!(
                    "{} / {}",
                    q!(c, 2, "kg·m/s", Signed),
                    q!(c, 1, "m/s", Signed)
                ),
                context
            )?
        );
        rule!(
            r"(?i)^a[n]? [a-z '-]+ of mass @(\d+) changes velocity from @(\d+) to @(\d+); (?:find|calculate) its momentum change$",
            "kg·m/s",
            c,
            format!(
                "{} * ({} - {})",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 3, "m/s", Signed),
                q!(c, 2, "m/s", Signed)
            )
        );
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ moving at @(\d+) is brought to rest; (?:find|determine) the magnitude of its momentum change$",
            "kg·m/s",
            c,
            format!(
                "abs({} * (0 m/s - {}))",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 2, "m/s", Signed)
            )
        );
        rule!(
            r"(?i)^two [a-z '-]+ of masses @(\d+) and @(\d+) move in the same direction at @(\d+) and @(\d+); (?:find|calculate) their total momentum$",
            "kg·m/s",
            c,
            {
                let v = q!(c, 3, "m/s", Signed);
                let u = q!(c, 4, "m/s", Signed);
                let v_value = self.compositions.quantity_value(&v, "m/s", context)?;
                let u_value = self.compositions.quantity_value(&u, "m/s", context)?;
                if v_value != 0.0 && u_value != 0.0 && v_value.signum() != u_value.signum() {
                    return Err(Error("invalid_physical_value".into()));
                }
                format!(
                    "{} * {v} + {} * {u}",
                    q!(c, 1, "kg", Nonnegative),
                    q!(c, 2, "kg", Nonnegative)
                )
            }
        );
        rule!(
            r"(?i)^two [a-z '-]+ have masses @(\d+) and @(\d+) and velocities @(\d+) and @(\d+); (?:find|calculate) their combined signed momentum$",
            "kg·m/s",
            c,
            format!(
                "{} * {} + {} * {}",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 3, "m/s", Signed),
                q!(c, 2, "kg", Nonnegative),
                q!(c, 4, "m/s", Signed)
            )
        );
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ (?:moves|travels|is launched|walks|has speed) at? ?@(\d+); (?:find|calculate|determine|what is) (?:its|their|the [a-z '-]+) kinetic energy$",
            "J",
            c,
            format!(
                "0.5 * {} * square({})",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 2, "m/s", Signed)
            )
        );
        rule!(
            r"(?i)^calculate the kinetic energy of a @(\d+) [a-z '-]+ moving at @(\d+)$",
            "J",
            c,
            format!(
                "0.5 * {} * square({})",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 2, "m/s", Signed)
            )
        );
        rule!(
            r"(?i)^how much kinetic energy does a @(\d+) [a-z '-]+ have at @(\d+)$",
            "J",
            c,
            format!(
                "0.5 * {} * square({})",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 2, "m/s", Signed)
            )
        );
        rule!(
            r"(?i)^what speed gives a @(\d+) [a-z '-]+ kinetic energy of @(\d+)$",
            "m/s",
            c,
            format!(
                "sqrt(2 * {} / {})",
                q!(c, 2, "J", Nonnegative),
                q!(c, 1, "kg", Positive)
            )
        );
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ has kinetic energy @(\d+); (?:find|determine) its (?:speed|velocity magnitude)$",
            "m/s",
            c,
            format!(
                "sqrt(2 * {} / {})",
                q!(c, 2, "J", Nonnegative),
                q!(c, 1, "kg", Positive)
            )
        );
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ speeds up from @(\d+) to @(\d+); (?:calculate|find) the change in kinetic energy$",
            "J",
            c,
            format!(
                "0.5 * {} * (square({}) - square({}))",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 3, "m/s", Signed),
                q!(c, 2, "m/s", Signed)
            )
        );
        rule!(
            r"(?i)^a [a-z '-]+ moving at @(\d+) has mass @(\d+); (?:find|calculate) its kinetic energy$",
            "J",
            c,
            format!(
                "0.5 * {} * square({})",
                q!(c, 2, "kg", Nonnegative),
                q!(c, 1, "m/s", Signed)
            )
        );

        // Gravitational energy requires an explicit g and a stated height change/reference.
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ is lifted @(\d+); use g = @(\d+) to (?:find|calculate) its gravitational potential energy gain$",
            "J",
            c,
            format!(
                "{} * {} * {}",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 3, "m/s²", Positive),
                q!(c, 2, "m", Nonnegative)
            )
        );
        rule!(
            r"(?i)^what height gives a @(\d+) mass gravitational potential energy of @(\d+) if g = @(\d+)$",
            "m",
            c,
            format!(
                "{} / ({} * {})",
                q!(c, 2, "J", Signed),
                q!(c, 1, "kg", Positive),
                q!(c, 3, "m/s²", Positive)
            )
        );
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ (descends|ascends) @(\d+); (?:calculate|find) the change in gravitational potential energy using g = @(\d+)$",
            "J",
            c,
            {
                let direction = if c[2].eq_ignore_ascii_case("descends") {
                    "-"
                } else {
                    ""
                };
                format!(
                    "{} * {} * {direction}{}",
                    q!(c, 1, "kg", Nonnegative),
                    q!(c, 4, "m/s²", Positive),
                    q!(c, 3, "m", Nonnegative)
                )
            }
        );
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ at height @(\d+) has what gravitational potential energy relative to the floor, with g = @(\d+)$",
            "J",
            c,
            format!(
                "{} * {} * {}",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 3, "m/s²", Positive),
                q!(c, 2, "m", Signed)
            )
        );
        rule!(
            r"(?i)^(?:find|calculate) the gravitational potential energy of a @(\d+) [a-z '-]+ raised @(\d+) with g = @(\d+)$",
            "J",
            c,
            format!(
                "{} * {} * {}",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 3, "m/s²", Positive),
                q!(c, 2, "m", Nonnegative)
            )
        );
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ is raised @(\d+); (?:calculate|find) its gravitational potential energy using g = @(\d+)$",
            "J",
            c,
            format!(
                "{} * {} * {}",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 3, "m/s²", Positive),
                q!(c, 2, "m", Nonnegative)
            )
        );

        // Net force, parallel/opposing work, and constant or average power.
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ accelerates at @(\d+)\. (?:find|calculate) its net force$",
            "N",
            c,
            format!(
                "{} * {}",
                q!(c, 1, "kg", Nonnegative),
                q!(c, 2, "m/s²", Signed)
            )
        );
        rule!(
            r"(?i)^a @(\d+) net force acts on a @(\d+) mass\. (?:find|calculate) its acceleration$",
            "m/s²",
            c,
            format!("{} / {}", q!(c, 1, "N", Signed), q!(c, 2, "kg", Positive))
        );
        rule!(
            r"(?i)^a @(\d+) net force produces acceleration @(\d+)\. (?:find|calculate) the mass$",
            "kg",
            c,
            self.mass(
                format!("{} / {}", q!(c, 1, "N", Signed), q!(c, 2, "m/s²", Signed)),
                context
            )?
        );
        rule!(
            r"(?i)^a constant @(\d+) force (acts along|opposes) a @(\d+) displacement\. (?:find|calculate) its (?:signed )?work$",
            "J",
            c,
            {
                let sign = if c[2].eq_ignore_ascii_case("opposes") {
                    "-"
                } else {
                    ""
                };
                format!(
                    "{sign}{} * {}",
                    q!(c, 1, "N", Nonnegative),
                    q!(c, 3, "m", Nonnegative)
                )
            }
        );
        rule!(
            r"(?i)^@(\d+) of work is done in @(\d+)\. (?:find|calculate) the average power$",
            "W",
            c,
            format!("{} / {}", q!(c, 1, "J", Signed), q!(c, 2, "s", Positive))
        );
        rule!(
            r"(?i)^a @(\d+) [a-z '-]+ operates for @(\d+) at constant power\. (?:find|calculate) the work$",
            "J",
            c,
            format!("{} * {}", q!(c, 1, "W", Signed), q!(c, 2, "s", Nonnegative))
        );
        Ok(None)
    }

    fn validate_report_field(
        &self,
        label: &str,
        target: &str,
        expression: &str,
        context: &Context,
    ) -> Result<(), Error> {
        let reference = match label {
            "net force" | "force" | "force magnitude" | "braking force magnitude" => "N",
            "work"
            | "potential-energy change"
            | "kinetic energy"
            | "kinetic energy lost"
            | "kinetic energy change"
            | "final kinetic energy"
            | "elastic potential energy" => "J",
            "average power" => "W",
            "final speed"
            | "speed"
            | "average speed"
            | "shared velocity"
            | "common velocity"
            | "final signed velocity"
            | "impact speed"
            | "speed for twice kinetic energy" => "m/s",
            "momentum" | "momentum change" | "momentum before impact" => "kg·m/s",
            "density" => "kg/m³",
            "distance" | "displacement" => "m",
            "acceleration" => "m/s²",
            "stopping time" | "elapsed time" | "fall time" => "seconds",
            _ => return Err(Error("invalid_expression".into())),
        };
        self.compositions
            .quantity_value(&format!("1 {target}"), reference, context)?;
        self.compositions
            .quantity_value(expression, target, context)?;
        Ok(())
    }

    fn report(&self, fields: &[(&str, &str, String)], context: &Context) -> Result<String, Error> {
        for (label, target, expression) in fields {
            self.validate_report_field(label, target, expression, context)?;
        }
        let result = format!(
            "mechanics_summary({})",
            fields
                .iter()
                .map(|(label, target, expression)| format!("{label}|{target}|{expression}"))
                .collect::<Vec<_>>()
                .join(";")
        );
        if result.len() > 4096 {
            return Err(Error("invalid_expression".into()));
        }
        Ok(result)
    }

    fn unit(&self, input: &str) -> bool {
        super::compound_units::factors(input, |leaf| self.compositions.units.unit(leaf).is_some())
            .is_some()
    }

    fn mass(&self, expression: String, context: &Context) -> Result<String, Error> {
        if self
            .compositions
            .quantity_value(&expression, "kg", context)?
            < 0.0
        {
            return Err(Error("invalid_physical_value".into()));
        }
        Ok(expression)
    }

    /// Replace complete physical measurements or typed function calls, preserving their spelling.
    /// Sentence rules then assign semantic roles; positional numbers alone never select a formula.
    fn measurements(&self, input: &str) -> (String, Vec<String>) {
        let mut shape = String::new();
        let mut quantities = Vec::new();
        let mut consumed = 0;
        let groups = super::syntax::groups(input).unwrap_or_default();
        for token in
            re!(r"\b[a-z]+\(|[+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?").find_iter(input)
        {
            if token.start() < consumed {
                continue;
            }
            if token.as_str().ends_with('(') {
                if super::named_quantities::has_function(token.as_str())
                    && let Some(group) = groups.iter().find(|group| group.start == token.end())
                {
                    shape.push_str(&input[consumed..token.start()]);
                    shape.push_str(&format!("@{}", quantities.len()));
                    quantities.push(input[token.start()..group.end + 1].to_string());
                    consumed = group.end + 1;
                }
                continue;
            }
            let suffix = &input[token.end()..];
            let mut end = None;
            for (index, character) in suffix.char_indices() {
                if index > 64 || matches!(character, ';' | ',' | '?' | '.') {
                    break;
                }
                if character.is_whitespace() && self.unit(suffix[..index].trim()) {
                    end = Some(index);
                }
            }
            let limit = suffix
                .char_indices()
                .find(|(i, c)| *i > 64 || matches!(c, ';' | ',' | '?' | '.'))
                .map(|(i, _)| i)
                .unwrap_or(suffix.len());
            if self.unit(suffix[..limit].trim()) {
                end = Some(limit);
            }
            let Some(end) = end else {
                continue;
            };
            let end = token.end() + end;
            shape.push_str(&input[consumed..token.start()]);
            shape.push_str(&format!("@{}", quantities.len()));
            quantities.push(input[token.start()..end].trim().to_string());
            consumed = end;
        }
        shape.push_str(&input[consumed..]);
        (
            shape.split_whitespace().collect::<Vec<_>>().join(" "),
            quantities,
        )
    }

    fn role(
        &self,
        index: &str,
        quantities: &[String],
        reference: &str,
        domain: Domain,
        context: &Context,
    ) -> Result<String, Error> {
        let quantity = index
            .parse::<usize>()
            .ok()
            .and_then(|i| quantities.get(i))
            .ok_or_else(|| Error("invalid_expression".into()))?;
        let value = self
            .compositions
            .quantity_value(quantity, reference, context)?;
        if (matches!(domain, Domain::Nonnegative | Domain::Positive) && value < 0.0)
            || (matches!(domain, Domain::Positive) && value == 0.0)
        {
            return Err(Error("invalid_physical_value".into()));
        }
        Ok(format!("({quantity})"))
    }
}

fn magnitude_if_speed(expression: String, sentence: &str) -> String {
    if sentence.to_ascii_lowercase().ends_with("speed") {
        format!("abs({expression})")
    } else {
        expression
    }
}