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
//! Complete paired shape/vector goals; only terminal formatting is local.
use super::{Geometry, norm};
use crate::{Context, Error, Outcome, Plugin, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};

impl Geometry {
    fn validate_field(
        &self,
        label: &str,
        target: &str,
        expression: &str,
        context: &Context,
    ) -> Result<(), Error> {
        if matches!(label, "components" | "unit vector" | "cross product") {
            if !target.is_empty() {
                return Err(Error("invalid_expression".into()));
            }
            let components = self.vector(expression, context)?;
            if label == "unit vector" {
                for component in &components {
                    self.engine.quantity_value(component, "1", context)?;
                }
            }
            return Ok(());
        }
        let reference = match label {
            "width"
            | "length"
            | "perimeter"
            | "perimeter before cutting"
            | "boundary length"
            | "other leg"
            | "circumference" => Some("m"),
            "area"
            | "remaining area"
            | "surface area"
            | "lateral surface area"
            | "standard uncertainty" => Some("m²"),
            "volume" | "one-rod volume" | "total volume" => Some("m³"),
            "cylinder mass" | "cuboid mass" | "one-rod mass" | "total mass" => Some("kg"),
            "direction angle" => Some("degrees"),
            "magnitude" | "dot product" => None,
            _ => return Err(Error("invalid_expression".into())),
        };
        if let Some(reference) = reference {
            self.engine.quantity_value(expression, reference, context)?;
            self.engine
                .quantity_value(&format!("1 {target}"), reference, context)?;
        }
        if !target.is_empty() {
            self.target(target)?;
            self.engine.quantity_value(expression, target, context)?;
        } else {
            self.engine
                .quantity_order(expression, expression, context)?;
        }
        Ok(())
    }

    fn display_field(
        &self,
        label: &str,
        target: &str,
        expression: &str,
        context: &Context,
    ) -> Result<String, Error> {
        if matches!(label, "components" | "unit vector" | "cross product") {
            let components = self.vector(expression, context)?;
            let values = components
                .iter()
                .map(|component| {
                    self.engine
                        .evaluate(component, context)
                        .ok_or_else(|| Error("invalid_expression".into()))?
                })
                .collect::<Result<Vec<_>, _>>()?;
            return Ok(format!("({})", values.join(", ")));
        }
        let formula = if target.is_empty() {
            expression.to_owned()
        } else {
            format!("({expression}) in {target}")
        };
        self.engine
            .evaluate(&formula, context)
            .ok_or_else(|| Error("invalid_expression".into()))?
    }

    pub(super) fn summary(
        &self,
        fields: &[(&str, &str, String)],
        context: &Context,
    ) -> Result<String, Error> {
        for (label, target, expression) in fields {
            self.validate_field(label, target, expression, context)?;
        }
        let result = format!(
            "geometry_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)
    }

    pub(super) fn evaluate_report(&self, input: &str, context: &Context) -> Outcome {
        let inner = input.strip_prefix("geometry_summary(")?.strip_suffix(')')?;
        Some((|| {
            if input.len() > 4096 {
                return Err(Error("invalid_expression".into()));
            }
            let fields = inner.split(';').collect::<Vec<_>>();
            if !(2..=3).contains(&fields.len())
                && !(fields.len() == 4
                    && fields
                        .iter()
                        .zip([
                            "one-rod volume|",
                            "one-rod mass|",
                            "total volume|",
                            "total mass|",
                        ])
                        .all(|(field, label)| field.starts_with(label)))
            {
                return Err(Error("invalid_expression".into()));
            }
            let mut validated = Vec::new();
            for field in fields {
                let parts = field.split('|').collect::<Vec<_>>();
                if parts.len() != 3 {
                    return Err(Error("invalid_expression".into()));
                }
                self.validate_field(parts[0], parts[1], parts[2], context)?;
                validated.push(parts);
            }
            let mut output = Vec::new();
            for parts in validated {
                let value = self.display_field(parts[0], parts[1], parts[2], context)?;
                output.push(format!("{}: {value}", parts[0]));
            }
            Ok(output.join("; "))
        })())
    }

    // A literal length supplies the default coordinate scale. Composite lengths
    // have no single authored display unit and use meters instead.
    pub(super) fn length_target(&self, input: &str) -> String {
        input
            .char_indices()
            .find_map(|(at, _)| {
                let unit = self.engine.units.unit(input[at..].trim())?;
                (unit.dimension == [1, 0, 0, 0, 0, 0, 0, 0]).then_some(unit.symbol)
            })
            .unwrap_or_else(|| "m".into())
    }

    fn read_length_coordinate(
        &self,
        role: &str,
        context: &Context,
    ) -> Result<super::super::model_coordinates::Coordinate, Error> {
        let error = match super::super::model_coordinates::read(role, "m", &self.engine, context) {
            Ok(coordinate) => return Ok(coordinate),
            Err(error) => error,
        };
        if error.0 != "incompatible_units" {
            return Err(error);
        }
        // Group only a complete scalar followed by one recognized length unit.
        // Typed compositions and every other error retain their owner.
        for (at, _) in role.char_indices().skip(1) {
            let coefficient = role[..at].trim();
            let unit = role[at..].trim();
            if self.engine.units.unit(unit).is_some()
                && self
                    .engine
                    .quantity_value(&format!("1 {unit}"), "m", context)
                    .is_ok()
                && self
                    .engine
                    .quantity_value(coefficient, "1", context)
                    .is_ok()
            {
                return super::super::model_coordinates::read(
                    &format!("({coefficient}) {unit}"),
                    "m",
                    &self.engine,
                    context,
                );
            }
        }
        Err(error)
    }

    fn typed_length_coordinate(
        coordinate: &super::super::model_coordinates::Coordinate,
    ) -> Result<String, Error> {
        if coordinate.authored {
            Ok(format!(
                "(rational({},{}) m)",
                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()));
            }
            Ok(format!("(real({value:e}) m)"))
        }
    }

    fn mass_in_kg(
        &self,
        mass: &BigRational,
        authored: bool,
        context: &Context,
    ) -> Result<String, Error> {
        self.mass_in_unit(mass, authored, "kg", context)
    }

    fn mass_in_unit(
        &self,
        mass: &BigRational,
        authored: bool,
        target: &str,
        context: &Context,
    ) -> Result<String, Error> {
        let scalar = if authored {
            format!("rational({},{})", mass.numer(), mass.denom())
        } else {
            let value = mass
                .to_f64()
                .filter(|value| value.is_finite())
                .ok_or_else(|| Error("numeric_overflow".into()))?;
            if value == 0.0 && !mass.is_zero() {
                return Err(Error("numeric_underflow".into()));
            }
            format!("real({value:e})")
        };
        self.output(format!("({scalar} kg)"), target, "kg", context)
    }

    fn mass_expression(mass: &BigRational, authored: bool) -> Result<String, Error> {
        Self::quantity_expression(mass, "kg", authored)
    }

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

    fn supplied_component_mass(
        &self,
        shape: &str,
        density: &str,
        pi: &super::super::model_coordinates::Coordinate,
        context: &Context,
    ) -> Result<(String, &'static str, BigRational, bool), Error> {
        let bounded = super::super::model_coordinates::bounded;
        let density =
            super::super::model_coordinates::read(density, "kg/m³", &self.engine, context)?;
        if !density.value.is_positive() {
            return Err(Error("invalid_geometry".into()));
        }
        if let Some(c) =
            re!(r"(?i)^a ([a-z]+) cylinder of radius (.+?) and height (.+?)$").captures(shape)
        {
            let radius = self.read_length_coordinate(&c[2], context)?;
            let height = self.read_length_coordinate(&c[3], context)?;
            if radius.value.is_negative() || height.value.is_negative() {
                return Err(Error("invalid_geometry".into()));
            }
            let mass = bounded(
                &pi.value * &radius.value * &radius.value * &height.value * &density.value,
            )?;
            return Ok((
                c[1].to_ascii_lowercase(),
                "cylinder mass",
                mass,
                radius.authored && height.authored && density.authored,
            ));
        }
        if let Some(c) =
            re!(r"(?i)^a ([a-z]+) cuboid (.+?) (?:by|×|x) (.+?) (?:by|×|x) (.+?)$").captures(shape)
        {
            let lengths = [2, 3, 4]
                .map(|at| self.read_length_coordinate(&c[at], context))
                .into_iter()
                .collect::<Result<Vec<_>, _>>()?;
            if lengths.iter().any(|length| length.value.is_negative()) {
                return Err(Error("invalid_geometry".into()));
            }
            let mass = bounded(
                lengths
                    .iter()
                    .fold(density.value.clone(), |value, length| value * &length.value),
            )?;
            return Ok((
                c[1].to_ascii_lowercase(),
                "cuboid mass",
                mass,
                lengths.iter().all(|length| length.authored) && density.authored,
            ));
        }
        Err(Error("invalid_expression".into()))
    }

    fn spherical_shell_mass(
        &self,
        outer: &super::super::model_coordinates::Coordinate,
        inner: &super::super::model_coordinates::Coordinate,
        density: &super::super::model_coordinates::Coordinate,
        pi: &super::super::model_coordinates::Coordinate,
        context: &Context,
    ) -> Result<String, Error> {
        if outer.value.is_negative()
            || inner.value.is_negative()
            || inner.value > outer.value
            || !density.value.is_positive()
            || !pi.authored
            || !pi.value.is_positive()
        {
            return Err(Error("invalid_geometry".into()));
        }
        let volume_difference =
            &outer.value * &outer.value * &outer.value - &inner.value * &inner.value * &inner.value;
        let mass = super::super::model_coordinates::bounded(
            BigRational::from_integer(4.into()) * &pi.value * &density.value * volume_difference
                / BigRational::from_integer(3.into()),
        )?;
        self.mass_in_kg(
            &mass,
            outer.authored && inner.authored && density.authored,
            context,
        )
    }

    pub(super) fn lower_report(
        &self,
        input: &str,
        context: &Context,
    ) -> Result<Option<String>, Error> {
        if input.len() > 4096 {
            return Ok(None);
        }
        if let Some(result) = self.lower_supplied(input, context)? {
            return Ok(Some(result));
        }
        if let Some(c) = re!(r"(?i)^for (.+?) identical [a-z]+ rods? each (.+?) long with circular diameter (.+?), density (.+?) and (?:pi|π)\s*=\s*(.+?), (?:report|give) one-rod volume and mass and total volume and mass using consistent SI units$").captures(input) {
            let count = super::super::integer_queries::value(&c[1])?;
            if !count.is_positive() {
                return Err(Error("invalid_geometry".into()));
            }
            let length = self.read_length_coordinate(&c[2], context)?;
            let diameter = self.read_length_coordinate(&c[3], context)?;
            let density = super::super::model_coordinates::read(&c[4], "kg/m³", &self.engine, context)?;
            let pi = super::super::model_coordinates::read(&c[5], "1", &self.engine, context)?;
            if length.value.is_negative() || diameter.value.is_negative()
                || !density.value.is_positive() || !pi.value.is_positive() || !pi.authored
            {
                return Err(Error("invalid_geometry".into()));
            }
            let bounded = super::super::model_coordinates::bounded;
            let radius = bounded(&diameter.value / BigRational::from_integer(2.into()))?;
            let volume = bounded(bounded(&pi.value * &radius)? * bounded(&radius * &length.value)?)?;
            let mass = bounded(&volume * &density.value)?;
            let count = BigRational::from_integer(count);
            let total_volume = bounded(&volume * &count)?;
            let total_mass = bounded(&mass * count)?;
            let authored = length.authored && diameter.authored && density.authored;
            return self.summary(&[
                ("one-rod volume", "m³", Self::quantity_expression(&volume, "m³", authored)?),
                ("one-rod mass", "kg", Self::mass_expression(&mass, authored)?),
                ("total volume", "m³", Self::quantity_expression(&total_volume, "m³", authored)?),
                ("total mass", "kg", Self::mass_expression(&total_mass, authored)?),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a composite block has (.+?) joined without overlap to (.+?)\. with (?:π|pi)\s*=\s*(.+?), ([a-z]+) density (.+?), and ([a-z]+) density (.+?), calculate both masses and their sum$").captures(input) {
            let pi = super::super::model_coordinates::read(&c[3], "1", &self.engine, context)?;
            if !pi.authored || !pi.value.is_positive() || c[4].eq_ignore_ascii_case(&c[6]) {
                return Err(Error("invalid_geometry".into()));
            }
            let material = |shape: &str| re!(r"(?i)^a ([a-z]+) (?:cylinder|cuboid)\b").captures(shape).map(|m| m[1].to_ascii_lowercase()).ok_or_else(|| Error("invalid_expression".into()));
            let first_name = material(&c[1])?;
            let second_name = material(&c[2])?;
            if first_name == second_name || ![&first_name, &second_name].iter().all(|name| name.eq_ignore_ascii_case(&c[4]) || name.eq_ignore_ascii_case(&c[6])) {
                return Err(Error("invalid_geometry".into()));
            }
            let first_density = if first_name.eq_ignore_ascii_case(&c[4]) { &c[5] } else { &c[7] };
            let second_density = if second_name.eq_ignore_ascii_case(&c[4]) { &c[5] } else { &c[7] };
            let first = self.supplied_component_mass(&c[1], first_density, &pi, context)?;
            let second = self.supplied_component_mass(&c[2], second_density, &pi, context)?;
            if first.1 == second.1 {
                return Err(Error("invalid_geometry".into()));
            }
            let mass = super::super::model_coordinates::bounded(&first.2 + &second.2)?;
            let supplied_mass_unit = |density: &str| re!(r"(?i)\b(kg|g)\s*/").captures(density).map(|m| m[1].to_ascii_lowercase());
            let target = match (supplied_mass_unit(&c[5]), supplied_mass_unit(&c[7])) {
                (Some(a), Some(b)) if a == b => a,
                _ => "kg".into(),
            };
            return self.summary(&[
                (first.1, &target, Self::mass_expression(&first.2, pi.authored && first.3)?),
                (second.1, &target, Self::mass_expression(&second.2, pi.authored && second.3)?),
                ("total mass", &target, Self::mass_expression(&mass, pi.authored && first.3 && second.3)?),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^compute the mass of a non-overlapping composite made from a cuboid (.+?) (?:×|x) (.+?) (?:×|x) (.+?) and a cylinder of radius (.+?) and height (.+?); use (?:pi|π)\s*=\s*(.+?), cuboid density (.+?), cylinder density (.+?), and return (grams|g|kilograms|kg)$").captures(input) {
            let a = self.read_length_coordinate(&c[1], context)?;
            let b = self.read_length_coordinate(&c[2], context)?;
            let depth = self.read_length_coordinate(&c[3], context)?;
            let radius = self.read_length_coordinate(&c[4], context)?;
            let height = self.read_length_coordinate(&c[5], context)?;
            let pi = super::super::model_coordinates::read(&c[6], "1", &self.engine, context)?;
            let cuboid_density = super::super::model_coordinates::read(&c[7], "kg/m³", &self.engine, context)?;
            let cylinder_density = super::super::model_coordinates::read(&c[8], "kg/m³", &self.engine, context)?;
            if [&a, &b, &depth, &radius, &height]
                .into_iter()
                .any(|length| length.value.is_negative())
                || !pi.authored || !pi.value.is_positive()
                || !cuboid_density.value.is_positive()
                || !cylinder_density.value.is_positive()
            {
                return Err(Error("invalid_geometry".into()));
            }
            let bounded = super::super::model_coordinates::bounded;
            let cuboid_mass = bounded(&a.value * &b.value * &depth.value * &cuboid_density.value)?;
            let cylinder_mass = bounded(&pi.value * &radius.value * &radius.value * &height.value * &cylinder_density.value)?;
            let mass = bounded(cuboid_mass + cylinder_mass)?;
            let authored = a.authored && b.authored && depth.authored && radius.authored
                && height.authored && pi.authored && cuboid_density.authored && cylinder_density.authored;
            return self.mass_in_unit(&mass, authored, &c[9], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^find the mass in (?:kilograms|kg) of a hollow sphere with outer diameter (.+?) and uniform wall thickness (.+?), given density (.+?) and (?:pi|π)\s*=\s*(.+?); use the difference of outer and inner spherical volumes and convert (.+?) to (.+?)$").captures(input) {
            let diameter = self.read_length_coordinate(&c[1], context)?;
            let wall = self.read_length_coordinate(&c[2], context)?;
            let density = super::super::model_coordinates::read(&c[3], "kg/m³", &self.engine, context)?;
            let pi = super::super::model_coordinates::read(&c[4], "1", &self.engine, context)?;
            let stated_left = super::super::model_coordinates::read(&c[5], "kg", &self.engine, context)?;
            let stated_right = super::super::model_coordinates::read(&c[6], "kg", &self.engine, context)?;
            if stated_left.value != stated_right.value || diameter.value.is_negative()
                || wall.value.is_negative() {
                return Err(Error("invalid_geometry".into()));
            }
            let outer = super::super::model_coordinates::Coordinate {
                value: super::super::model_coordinates::bounded(
                    &diameter.value / BigRational::from_integer(2.into()),
                )?,
                authored: diameter.authored,
            };
            if wall.value > outer.value {
                return Err(Error("invalid_geometry".into()));
            }
            let inner = super::super::model_coordinates::Coordinate {
                value: super::super::model_coordinates::bounded(&outer.value - &wall.value)?,
                authored: diameter.authored && wall.authored,
            };
            return self.spherical_shell_mass(&outer, &inner, &density, &pi, context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a spherical shell has outer radius (.+?) and inner radius (.+?), with uniform density (.+?)\. use (?:pi|π)\s*=\s*(.+?) and (?:calculate|find) its mass, treating it as the volume difference of two spheres$").captures(input) {
            let outer = self.read_length_coordinate(&c[1], context)?;
            let inner = self.read_length_coordinate(&c[2], context)?;
            let density = super::super::model_coordinates::read(&c[3], "kg/m³", &self.engine, context)?;
            let pi = super::super::model_coordinates::read(&c[4], "1", &self.engine, context)?;
            return self.spherical_shell_mass(&outer, &inner, &density, &pi, context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a plate consists of a (.+?) by (.+?) rectangle plus a semicircle attached along one (.+?) edge; semicircle radius is (.+?), total uniform thickness is (.+?), density is (.+?), and (?:pi|π)\s*=\s*(.+?)\. (?:find|calculate) the total mass, with the pieces non-overlapping$").captures(input) {
            let width = self.read_length_coordinate(&c[1], context)?;
            let height = self.read_length_coordinate(&c[2], context)?;
            let edge = self.read_length_coordinate(&c[3], context)?;
            let radius = self.read_length_coordinate(&c[4], context)?;
            let thickness = self.read_length_coordinate(&c[5], context)?;
            let density = super::super::model_coordinates::read(&c[6], "kg/m³", &self.engine, context)?;
            let pi = super::super::model_coordinates::read(&c[7], "1", &self.engine, context)?;
            if !width.value.is_positive() || !height.value.is_positive()
                || radius.value.is_negative() || thickness.value.is_negative()
                || !density.value.is_positive() || !pi.authored || !pi.value.is_positive()
                || (edge.value != width.value && edge.value != height.value)
                || edge.value != &radius.value * BigRational::from_integer(2.into()) {
                return Err(Error("invalid_geometry".into()));
            }
            let area = &width.value * &height.value
                + &pi.value * &radius.value * &radius.value / BigRational::from_integer(2.into());
            let mass = super::super::model_coordinates::bounded(area * &thickness.value * &density.value)?;
            return self.mass_in_kg(
                &mass,
                width.authored && height.authored && edge.authored && radius.authored
                    && thickness.authored && density.authored,
                context,
            ).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a (.+?) by (.+?) plate has a radius-(.+?) circular hole centered inside it\. the rectangle is [a-z]+, density (.+?), and the hole is air\. with plate thickness (.+?) and (?:π|pi)\s*=\s*(.+?), find the plate mass$").captures(input) {
            let width = self.read_length_coordinate(&c[1], context)?;
            let height = self.read_length_coordinate(&c[2], context)?;
            let radius = self.read_length_coordinate(&c[3], context)?;
            let density = super::super::model_coordinates::read(&c[4], "g/cm³", &self.engine, context)?;
            let thickness = self.read_length_coordinate(&c[5], context)?;
            let pi = super::super::model_coordinates::read(&c[6], "1", &self.engine, context)?;
            if !width.value.is_positive() || !height.value.is_positive()
                || radius.value.is_negative() || thickness.value.is_negative()
                || !density.value.is_positive() || !pi.authored || !pi.value.is_positive()
                || &radius.value * num_rational::BigRational::from_integer(2.into()) > width.value
                || &radius.value * num_rational::BigRational::from_integer(2.into()) > height.value {
                return Err(Error("invalid_geometry".into()));
            }
            let bounded = super::super::model_coordinates::bounded;
            let area = bounded(
                bounded(&width.value * &height.value)?
                    - bounded(&pi.value * &radius.value * &radius.value)?,
            )?;
            if area.is_negative() {
                return Err(Error("invalid_geometry".into()));
            }
            let volume = bounded(area * &thickness.value)?;
            let cubic_centimeters = super::super::model_coordinates::read("1 m³", "cm³", &self.engine, context)?.value;
            let mass = bounded(bounded(volume * cubic_centimeters)? * &density.value)?;
            let scalar = if width.authored && height.authored && radius.authored
                && density.authored && thickness.authored {
                format!("rational({},{})", mass.numer(), mass.denom())
            } else {
                let value = mass.to_f64().filter(|value| value.is_finite())
                    .ok_or_else(|| Error("numeric_overflow".into()))?;
                if value == 0.0 && !mass.is_zero() {
                    return Err(Error("numeric_underflow".into()));
                }
                format!("real({value:e})")
            };
            return self.output(format!("({scalar} g)"), "g", "g", context).map(Some);
        }
        let boundary = re!(r"(?i)^a rectangle (.+?) by (.+?) has a circular hole of radius (.+?); with (?:π|pi)\s*=\s*(.+?), report (remaining area and boundary length including the hole circumference|boundary length including the hole circumference and remaining area)$").captures(input);
        let material_boundary = boundary.is_some();
        let boundary_first = boundary
            .as_ref()
            .is_some_and(|c| c[5].to_ascii_lowercase().starts_with("boundary"));
        if let Some(c) = boundary.or_else(|| re!(r"(?i)^a rectangular plate measures (.+?) by (.+?) and has a circular hole of radius (.+?) centered inside it\. using (?:π|pi)\s*=\s*(.+?), report remaining area and the plate perimeter before cutting$").captures(input)) {
            let width = self.read_length_coordinate(&c[1], context)?;
            let height = self.read_length_coordinate(&c[2], context)?;
            let radius = self.read_length_coordinate(&c[3], context)?;
            let pi = super::super::model_coordinates::read(&c[4], "1", &self.engine, context)?;
            if !width.value.is_positive() || !height.value.is_positive()
                || radius.value.is_negative() || !pi.authored || !pi.value.is_positive()
                || &radius.value * num_rational::BigRational::from_integer(2.into()) > width.value
                || &radius.value * num_rational::BigRational::from_integer(2.into()) > height.value {
                return Err(Error("invalid_geometry".into()));
            }
            let (area, perimeter) = if width.authored && height.authored && radius.authored {
                let bounded = super::super::model_coordinates::bounded;
                let plate = bounded(&width.value * &height.value)?;
                let hole = bounded(&pi.value * &radius.value * &radius.value)?;
                let area = bounded(plate - hole)?;
                let two = num_rational::BigRational::from_integer(2.into());
                let outer = bounded((&width.value + &height.value) * &two)?;
                let perimeter = if material_boundary {
                    let hole_boundary = bounded(&pi.value * &radius.value * &two)?;
                    bounded(outer + hole_boundary)?
                } else {
                    outer
                };
                (
                    format!("rational({},{}) m²", area.numer(), area.denom()),
                    format!("rational({},{}) m", perimeter.numer(), perimeter.denom()),
                )
            } else {
                let width = Self::typed_length_coordinate(&width)?;
                let height = Self::typed_length_coordinate(&height)?;
                let radius = Self::typed_length_coordinate(&radius)?;
                let pi = format!("rational({},{})", pi.value.numer(), pi.value.denom());
                (
                    format!("{width}*{height}-{pi}*square({radius})"),
                    if material_boundary {
                        format!("2*({width}+{height})+2*{pi}*{radius}")
                    } else {
                        format!("2*({width}+{height})")
                    },
                )
            };
            let unit = self.length_target(&c[1]);
            let area_unit = format!("{unit}²");
            let mut fields = [
                ("remaining area", area_unit.as_str(), area),
                (if material_boundary { "boundary length" } else { "perimeter before cutting" }, unit.as_str(), perimeter),
            ];
            if boundary_first {
                fields.swap(0, 1);
            }
            return self.summary(&fields, context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a cylinder has radius (.+?) and height (.+?); using (?:π|pi)\s*=\s*(.+?), compute volume and lateral surface area$").captures(input) {
            let radius = self.read_length_coordinate(&c[1], context)?;
            let height = self.read_length_coordinate(&c[2], context)?;
            let pi = super::super::model_coordinates::read(&c[3], "1", &self.engine, context)?;
            if radius.value.is_negative() || height.value.is_negative() || !pi.authored
                || !pi.value.is_positive() {
                return Err(Error("invalid_geometry".into()));
            }
            let (volume, lateral) = if radius.authored && height.authored {
                let bounded = super::super::model_coordinates::bounded;
                let side = bounded(&pi.value * &radius.value * &height.value)?;
                let volume = bounded(&side * &radius.value)?;
                let lateral = bounded(side * num_rational::BigRational::from_integer(2.into()))?;
                (
                    format!("rational({},{}) m³", volume.numer(), volume.denom()),
                    format!("rational({},{}) m²", lateral.numer(), lateral.denom()),
                )
            } else {
                let radius = Self::typed_length_coordinate(&radius)?;
                let height = Self::typed_length_coordinate(&height)?;
                let pi = format!("rational({},{})", pi.value.numer(), pi.value.denom());
                (
                    format!("{pi}*square({radius})*{height}"),
                    format!("2*{pi}*{radius}*{height}"),
                )
            };
            return self.summary(&[
                ("volume", "m³", volume),
                ("lateral surface area", "m²", lateral),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a rectangular plate measures (.+?) by (.+?), each dimension with independent standard uncertainty (.+?); using first-order uncertainty propagation, report area and propagated standard uncertainty$").captures(input) {
            let unit = self.length_target(&c[1]);
            let read = |role: &str| {
                super::super::model_coordinates::read(role, &unit, &self.engine, context)
            };
            let a = read(&c[1])?;
            let b = read(&c[2])?;
            let uncertainty = read(&c[3])?;
            if !a.value.is_positive() || !b.value.is_positive() || uncertainty.value.is_negative() {
                return Err(Error("invalid_geometry".into()));
            }
            let bounded = super::super::model_coordinates::bounded;
            let first = bounded(&b.value * &uncertainty.value)?;
            let second = bounded(&a.value * &uncertainty.value)?;
            let variance = bounded(bounded(&first * &first)? + bounded(&second * &second)?)?;
            let root = super::super::model_coordinates::computed_root(variance, |expression| {
                self.engine.quantity_value(expression, "1", context)
            })?;
            let value = root.to_f64().filter(|value| value.is_finite())
                .ok_or_else(|| Error("numeric_overflow".into()))?;
            if !root.is_zero() && value == 0.0 {
                return Err(Error("numeric_underflow".into()));
            }
            let target = format!("{unit}²");
            return self.summary(&[
                ("area", &target, format!("({})*({})", &c[1], &c[2])),
                ("standard uncertainty", &target, format!("real({value:e}) {target}")),
            ], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a box measures (.+?) by (.+?) by (.+?); find its (volume|total surface area) in (.+?) and its (volume|total surface area) in (.+)$").captures(input) {
            if c[4].eq_ignore_ascii_case(&c[6]) {
                return Err(Error("invalid_expression".into()));
            }
            let a = self.length(&c[1], context)?.0;
            let b = self.length(&c[2], context)?.0;
            let height = self.length(&c[3], context)?.0;
            let volume = format!("{a}*{b}*{height}");
            let area = format!("2*({a}*{b}+{a}*{height}+{b}*{height})");
            let fields = [(&c[4], &c[5]), (&c[6], &c[7])].map(|(goal, target)| {
                if goal.eq_ignore_ascii_case("volume") {
                    ("volume", target, volume.clone())
                } else {
                    ("surface area", target, area.clone())
                }
            });
            return self.summary(&fields, context).map(Some);
        }
        if let Some(c) = re!(
            r"(?i)^a rectangle has perimeter (.+?) and length (.+?); what are its width and area$"
        )
        .captures(input)
        {
            let perimeter =
                super::super::model_coordinates::read(&c[1], "m", &self.engine, context)?;
            let length = super::super::model_coordinates::read(&c[2], "m", &self.engine, context)?;
            let width = super::super::model_coordinates::bounded(
                &perimeter.value / num_rational::BigRational::from_integer(2.into())
                    - &length.value,
            )?;
            if !length.value.is_positive() || !width.is_positive() {
                return Err(Error("invalid_geometry".into()));
            }
            let target = self.length_target(&c[2]);
            let width = format!("({})/2-({})", &c[1], &c[2]);
            return self
                .summary(
                    &[
                        ("width", &target, width.clone()),
                        (
                            "area",
                            &format!("{target}²"),
                            format!("({})*({width})", &c[2]),
                        ),
                    ],
                    context,
                )
                .map(Some);
        }
        if let Some(c) = re!(r"(?i)^a circular [a-z '-]+ has radius (.+?); using (?:pi|π) exactly as (.+?), what are its area and circumference$").captures(input) {
            let (radius, value) = self.length(&c[1], context)?;
            if value == 0.0 {
                return Err(Error("invalid_geometry".into()));
            }
            let pi = self.constant(&c[2], context)?;
            let target = self.length_target(&c[1]);
            return self.summary(&[("area", &format!("{target}²"), format!("{pi}*square({radius})")),
                ("circumference", &target, format!("2*{pi}*{radius}"))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^what is the vector sum of (\(.+\)) and (\(.+\)), and what is the magnitude of the resulting vector$").captures(input) {
            let a = self.vector(&c[1], context)?;
            let b = self.vector(&c[2], context)?;
            if a.len() != b.len() {
                return Err(Error("invalid_vector".into()));
            }
            self.engine.quantity_order(&a[0], &b[0], context)?;
            let components = a.iter().zip(&b).map(|(a,b)| format!("({a}+{b})")).collect::<Vec<_>>();
            return self.summary(&[("components", "", format!("({})", components.join(","))),
                ("magnitude", "", norm(&components))], context).map(Some);
        }
        if let Some(c) = re!(
            r"(?i)^a displacement vector is (\(.+\)) (.+?); give its magnitude and its unit vector$"
        )
        .captures(input)
        {
            self.target(&c[2])?;
            self.engine
                .quantity_value(&format!("1 {}", &c[2]), "m", context)?;
            let scalars = self.vector(&c[1], context)?;
            for scalar in &scalars {
                self.engine.quantity_value(scalar, "1", context)?;
            }
            let mut zero = true;
            for scalar in &scalars {
                zero &= super::super::model_coordinates::read(scalar, "1", &self.engine, context)?
                    .value
                    .is_zero();
            }
            if zero {
                return Err(Error("division_by_zero".into()));
            }
            let components = scalars
                .iter()
                .map(|part| format!("({part}* (1 {}))", &c[2]))
                .collect::<Vec<_>>();
            let magnitude = norm(&components);
            let direction = components
                .iter()
                .map(|part| format!("{part}/({magnitude})"))
                .collect::<Vec<_>>();
            return self
                .summary(
                    &[
                        ("magnitude", "m", magnitude),
                        ("unit vector", "", format!("({})", direction.join(","))),
                    ],
                    context,
                )
                .map(Some);
        }
        Ok(None)
    }
}