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
//! Supplied thin-lens and planar-refraction models share typed exact coordinates.
mod wording;
use super::{
    compositions::Compositions,
    model_coordinates::{self, Coordinate},
    named_quantities, syntax,
};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};

#[derive(Default)]
pub struct OpticsQueries {
    engine: Compositions,
}
impl Plugin for OpticsQueries {
    fn rewrite_call(
        &self,
        name: &str,
        arguments: &str,
        context: &Context,
        position: ModelPosition,
    ) -> Outcome {
        if !calls().is_match(&format!("{name}(")) {
            return None;
        }
        Some(
            Request {
                engine: &self.engine,
                context,
            }
            .call(name, arguments, position),
        )
    }
    fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
        Request {
            engine: &self.engine,
            context,
        }
        .wording(input)
    }
    fn rewrite(&self, input: &str, context: &Context) -> Outcome {
        let request = Request {
            engine: &self.engine,
            context,
        };
        let expression = match syntax::rewrite_groups(input, |s| request.wording(s)) {
            Some(Ok(s)) => s,
            Some(Err(e)) => return Some(Err(e)),
            None => input.into(),
        };
        let whole = syntax::ungroup(&expression);
        let standalone_angle = calls().find(whole).is_some_and(|found| {
            found.start() == 0
                && matches!(
                    whole[..found.end() - 1]
                        .trim()
                        .to_ascii_lowercase()
                        .as_str(),
                    "snell_angle" | "critical_angle"
                )
                && syntax::groups(whole).is_some_and(|groups| {
                    groups.len() == 1
                        && groups[0].start == found.end()
                        && groups[0].end + 1 == whole.len()
                })
        });
        match syntax::rewrite_calls(&expression, calls(), |name, arguments| {
            request.call(name.trim(), arguments, ModelPosition::Operand)
        }) {
            Ok(s) if s != input => Some(Ok(if standalone_angle {
                format!("({s}) in rad")
            } else {
                s
            })),
            Err(e) => Some(Err(e)),
            _ => None,
        }
    }
    fn evaluate(&self, input: &str, context: &Context) -> Outcome {
        let input = syntax::ungroup(input);
        if input.contains("optics_answer(") {
            return Some((|| {
                let answer = input
                    .strip_prefix("optics_answer(")
                    .and_then(|s| s.strip_suffix(')'))
                    .ok_or_else(invalid)?;
                match answer {
                    "no finite image distance" | "total internal reflection" => Ok(answer.into()),
                    _ => Err(invalid()),
                }
            })());
        }
        if !input.contains("optics_report(") {
            return None;
        }
        Some((|| {
            let fields = input
                .strip_prefix("optics_report(")
                .and_then(|s| s.strip_suffix(')'))
                .ok_or_else(invalid)?;
            let fields: Vec<_> = fields.split(';').collect();
            if !(2..=4).contains(&fields.len()) {
                return Err(invalid());
            }
            let mut answers = Vec::new();
            for field in fields {
                let (label, expression) = field.split_once('|').ok_or_else(invalid)?;
                let (label, target) = label
                    .split_once('@')
                    .map_or((label, None), |(label, unit)| (label, Some(unit)));
                let unit = match label {
                    "image distance" | "object distance" | "image height" | "focal length" => "m",
                    "magnification" | "magnification magnitude" => "1",
                    "critical angle" | "refracted angle" => "°",
                    "refraction possible" | "total internal reflection" => {
                        if target.is_some() || !matches!(expression, "true" | "false") {
                            return Err(invalid());
                        }
                        answers.push(format!("{label}: {expression}"));
                        continue;
                    }
                    "orientation" => {
                        if target.is_some() || !matches!(expression, "upright" | "inverted") {
                            return Err(invalid());
                        }
                        answers.push(format!("{label}: {expression}"));
                        continue;
                    }
                    _ => return Err(invalid()),
                };
                self.engine.quantity_value(expression, unit, context)?;
                let target = target.unwrap_or(unit);
                self.engine
                    .quantity_value(&target_quantity(target), unit, context)?;
                let expression = if target == "1" {
                    expression.into()
                } else {
                    format!("({expression}) in {target}")
                };
                let answer = self
                    .engine
                    .evaluate(&expression, context)
                    .ok_or_else(invalid)??;
                let suffix = if label == "magnification magnitude" {
                    "%"
                } else {
                    ""
                };
                answers.push(format!("{label}: {answer}{suffix}"));
            }
            Ok(answers.join("; "))
        })())
    }
}
fn calls() -> &'static regex::Regex {
    re!(
        r"(?i)\b(?:lens_image_distance|lens_object_distance|lens_focal_length|lens_magnification|snell_angle|critical_angle)\s*\("
    )
}
fn invalid() -> Error {
    Error("invalid_expression".into())
}
fn physical() -> Error {
    Error("invalid_physical_quantity".into())
}
fn target_quantity(unit: &str) -> String {
    if unit == "1" {
        "1".into()
    } else {
        format!("1 {unit}")
    }
}
fn nonzero(value: &BigRational) -> Result<(), Error> {
    if value.is_zero() {
        Err(Error("division_by_zero".into()))
    } else {
        Ok(())
    }
}
fn sinc(value: f64) -> f64 {
    if value == 0.0 {
        1.0
    } else {
        value.sin() / value
    }
}
fn normalized_grazing_gap(
    ratio: &BigRational,
    beta: &BigRational,
    delta: &BigRational,
) -> Result<(f64, f64), Error> {
    let scale = beta.abs().max(delta.abs());
    let numeric = || Error("numeric_overflow".into());
    let normalized_beta = model_coordinates::bounded(beta / &scale)?
        .to_f64()
        .ok_or_else(numeric)?;
    let normalized_delta = model_coordinates::bounded(delta / &scale)?
        .to_f64()
        .ok_or_else(numeric)?;
    let radians = delta.to_f64().ok_or_else(numeric)?.to_radians();
    // Divide the grazing gap by a shared exact scale before rounding its terms.
    // sinc retains the linear term even when the original angular offset underflows.
    let correction = normalized_delta
        * (std::f64::consts::PI / 180.0)
        * (radians * sinc(radians / 2.0).powi(2) / 4.0 - 3.0f64.sqrt() / 2.0 * sinc(radians));
    let gap = ratio
        .to_f64()
        .ok_or_else(numeric)?
        .mul_add(correction, normalized_beta);
    Ok((gap, scale.to_f64().ok_or_else(numeric)?))
}
fn coordinate(value: BigRational, authored: bool) -> Result<Coordinate, Error> {
    Ok(Coordinate {
        value: model_coordinates::bounded(value)?,
        authored,
    })
}
fn report<S: AsRef<str>>(fields: &[(S, String)]) -> String {
    format!(
        "optics_report({})",
        fields
            .iter()
            .map(|(label, s)| format!("{}|{s}", label.as_ref()))
            .collect::<Vec<_>>()
            .join(";")
    )
}
struct Request<'a> {
    engine: &'a Compositions,
    context: &'a Context,
}
enum Refraction {
    Transmitted(String),
    TotalInternalReflection,
}
impl Request<'_> {
    fn read(&self, input: &str, unit: &str) -> Result<Coordinate, Error> {
        model_coordinates::read(input, unit, self.engine, self.context)
    }
    fn length(&self, input: &str) -> Result<Coordinate, Error> {
        let value = self.read(input, "m")?;
        nonzero(&value.value)?;
        Ok(value)
    }
    fn index(&self, input: &str) -> Result<Coordinate, Error> {
        let value = self.read(input, "1")?;
        if value.value <= BigRational::zero() {
            return Err(physical());
        }
        Ok(value)
    }
    fn emit(&self, value: &Coordinate, unit: &str) -> Result<String, Error> {
        let rational = format!("rational({},{})", value.value.numer(), value.value.denom());
        let expression = if unit == "1" {
            rational
        } else {
            format!("(({rational}) {unit})")
        };
        if expression.len() > 4096 {
            return Err(Error("integer_limit".into()));
        }
        let computed = self
            .engine
            .quantity_value(&expression, unit, self.context)?;
        Ok(if value.authored {
            expression
        } else {
            self.real(computed, unit)
        })
    }
    fn real(&self, value: f64, unit: &str) -> String {
        if unit == "1" {
            format!("real({value:e})")
        } else {
            format!("(real({value:e})*(1 {unit}))")
        }
    }
    fn image(&self, f: &Coordinate, object: &Coordinate) -> Result<Coordinate, Error> {
        let difference = &object.value - &f.value;
        nonzero(&difference)?;
        coordinate(
            &f.value * &object.value / difference,
            f.authored && object.authored,
        )
    }
    fn magnification(&self, object: &Coordinate, image: &Coordinate) -> Result<Coordinate, Error> {
        nonzero(&object.value)?;
        coordinate(
            -&image.value / &object.value,
            object.authored && image.authored,
        )
    }
    fn focal(&self, object: &Coordinate, image: &Coordinate) -> Result<Coordinate, Error> {
        let sum = &object.value + &image.value;
        nonzero(&sum)?;
        coordinate(
            &object.value * &image.value / sum,
            object.authored && image.authored,
        )
    }
    fn lens_inverse_answer(
        &self,
        first: &str,
        image: &str,
        target: &str,
        kind: &str,
        paired: bool,
    ) -> Result<String, Error> {
        let first = self.length(first)?;
        let image = self.length(image)?;
        let (object, result, label) = if target == "object" {
            self.focal_kind(&first, kind)?;
            let object = self.image(&first, &image)?;
            let result = self.emit(&object, "m")?;
            (object, result, "object distance")
        } else {
            let f = self.focal(&first, &image)?;
            self.focal_kind(&f, kind)?;
            let result = self.emit(&f, "m")?;
            (first, result, "focal length")
        };
        if !paired {
            return Ok(format!("{result} in m"));
        }
        let m = self.emit(&self.magnification(&object, &image)?, "1")?;
        Ok(report(&[(label, result), ("magnification", m)]))
    }
    fn focal_kind(&self, f: &Coordinate, kind: &str) -> Result<(), Error> {
        if kind.eq_ignore_ascii_case("converging") && f.value.is_negative()
            || kind.eq_ignore_ascii_case("diverging") && f.value.is_positive()
        {
            return Err(physical());
        }
        Ok(())
    }
    fn lens_answer(
        &self,
        f: &str,
        object: &str,
        height: Option<&str>,
        kind: &str,
        output: &str,
    ) -> Result<String, Error> {
        let f = self.length(f)?;
        self.focal_kind(&f, kind)?;
        let object = self.length(object)?;
        let image = self.image(&f, &object)?;
        let di = self.emit(&image, "m")?;
        if output == "distance" {
            return Ok(format!("{di} in m"));
        }
        let m = self.magnification(&object, &image)?;
        let magnification = self.emit(&m, "1")?;
        if output == "magnification" {
            return Ok(magnification);
        }
        let mut fields = vec![("image distance", di), ("magnification", magnification)];
        if output == "absolute_report" {
            let magnitude = coordinate(
                m.value.abs() * BigRational::from_integer(100.into()),
                m.authored,
            )?;
            fields.push(("magnification magnitude", self.emit(&magnitude, "1")?));
        }
        if let Some(height) = height {
            let height = self.read(height, "m")?;
            if height.value.is_negative() {
                return Err(physical());
            }
            let hi = coordinate(&m.value * height.value, m.authored && height.authored)?;
            fields.push(("image height", self.emit(&hi, "m")?));
        }
        Ok(report(&fields))
    }
    fn lens_height_report(
        &self,
        f: &str,
        object: &str,
        height: &str,
        kind: &str,
        fields: &[(String, String)],
    ) -> Result<String, Error> {
        self.lens_report(f, object, Some(height), kind, fields)
    }
    fn lens_report(
        &self,
        f: &str,
        object: &str,
        height: Option<&str>,
        kind: &str,
        fields: &[(String, String)],
    ) -> Result<String, Error> {
        let f = self.length(f)?;
        self.focal_kind(&f, kind)?;
        let object = self.length(object)?;
        let height = height.map(|h| self.read(h, "m")).transpose()?;
        if height.as_ref().is_some_and(|h| h.value.is_negative()) {
            return Err(physical());
        }
        let mut answers = Vec::new();
        for (label, target) in fields {
            let unit = match label.as_str() {
                "focal length" | "object distance" | "image distance" | "image height" => "m",
                "magnification" => "1",
                _ => return Err(invalid()),
            };
            self.engine
                .quantity_value(&target_quantity(target), unit, self.context)?;
            // Supplied roles are validated above; derive only requested outputs.
            let value = match label.as_str() {
                "focal length" => self.emit(&f, unit)?,
                "object distance" => self.emit(&object, unit)?,
                "image distance" => self.emit(&self.image(&f, &object)?, unit)?,
                _ => {
                    let image = self.image(&f, &object)?;
                    let magnification = self.magnification(&object, &image)?;
                    if label == "magnification" {
                        self.emit(&magnification, unit)?
                    } else {
                        let height = height.as_ref().ok_or_else(invalid)?;
                        let image_height = coordinate(
                            &magnification.value * &height.value,
                            magnification.authored && height.authored,
                        )?;
                        self.emit(&image_height, unit)?
                    }
                }
            };
            answers.push((format!("{label}@{target}"), value));
        }
        if let [(_, value)] = answers.as_slice() {
            let target = &fields[0].1;
            Ok(if target == "1" {
                value.to_owned()
            } else {
                format!("({value}) in {target}")
            })
        } else {
            Ok(report(&answers))
        }
    }
    fn snell_from_basis(
        &self,
        n1: &str,
        n2: &str,
        incident: &str,
        basis: &str,
    ) -> Result<String, Error> {
        self.snell_from_basis_output(n1, n2, incident, basis, "angle")
    }
    fn snell_from_basis_output(
        &self,
        n1: &str,
        n2: &str,
        incident: &str,
        basis: &str,
        output: &str,
    ) -> Result<String, Error> {
        if basis.eq_ignore_ascii_case("normal") {
            return self.snell_answer(n1, n2, incident, output);
        }
        let angle = self.read(incident, "°")?;
        if angle.value.is_negative() || angle.value > BigRational::from_integer(90.into()) {
            return Err(physical());
        }
        let normal = coordinate(
            BigRational::from_integer(90.into()) - angle.value,
            angle.authored,
        )?;
        self.snell_answer(n1, n2, &self.emit(&normal, "°")?, output)
    }
    fn refraction(&self, n1: &str, n2: &str, incident: &str) -> Result<Refraction, Error> {
        let n1 = self.index(n1)?;
        let n2 = self.index(n2)?;
        let theta = self.read(incident, "°")?;
        if theta.value.is_negative() || theta.value > BigRational::from_integer(90.into()) {
            return Err(physical());
        }
        if n1.value == n2.value {
            // Equal indices preserve the validated incident coordinate and its provenance.
            return self.emit(&theta, "°").map(Refraction::Transmitted);
        }
        let ratio = model_coordinates::bounded(n1.value / n2.value)?;
        let half = BigRational::new(1.into(), 2.into());
        let delta = &theta.value - BigRational::from_integer(30.into());
        if theta.authored && delta.is_positive() && ratio >= BigRational::from_integer(2.into()) {
            return Ok(Refraction::TotalInternalReflection);
        }
        // Near sin30=1/2, round the small offset and grazing gap, not the full
        // authored angle. This avoids losing a genuine side of the TIR boundary.
        if theta.authored
            && !delta.is_zero()
            && delta.abs() <= BigRational::from_integer(1.into())
            && ratio >= BigRational::new(3.into(), 2.into())
            && ratio <= BigRational::new(5.into(), 2.into())
        {
            let beta = BigRational::from_integer(1.into()) - &ratio * half;
            let (gap, scale) = normalized_grazing_gap(&ratio, &beta, &delta)?;
            if gap < 0.0 {
                return Ok(Refraction::TotalInternalReflection);
            }
            // Classify the sign before reconstructing magnitude. Underflow here
            // means the final angle rounds to90 degrees, not a change of domain.
            let gap = gap * scale;
            let angle = 90.0 - 2.0 * (gap / 2.0).sqrt().asin().to_degrees();
            let expression = self.real(angle, "°");
            self.engine.quantity_value(&expression, "°", self.context)?;
            return Ok(Refraction::Transmitted(expression));
        }
        // The rational sine values on this branch preserve exact authored grazing
        // boundaries. Other trigonometric evaluations retain binary64 provenance.
        let sine = if theta.authored && theta.value.is_zero() {
            BigRational::zero()
        } else if theta.authored && theta.value == BigRational::from_integer(30.into()) {
            BigRational::new(1.into(), 2.into())
        } else if theta.authored && theta.value == BigRational::from_integer(90.into()) {
            BigRational::from_integer(1.into())
        } else {
            let radians = self.engine.quantity_value(incident, "rad", self.context)?;
            BigRational::from_float(radians.sin())
                .ok_or_else(|| Error("numeric_overflow".into()))?
        };
        let sine = model_coordinates::bounded(ratio * sine)?;
        if sine > BigRational::from_integer(1.into()) {
            Ok(Refraction::TotalInternalReflection)
        } else {
            self.angle(&sine).map(Refraction::Transmitted)
        }
    }
    fn angle(&self, sine: &BigRational) -> Result<String, Error> {
        if sine > &BigRational::from_integer(1.into()) {
            return Err(physical());
        }
        let value = Coordinate {
            value: sine.clone(),
            authored: true,
        };
        let scalar = self.emit(&value, "1")?;
        let sine = self.engine.quantity_value(&scalar, "1", self.context)?;
        let angle = sine.asin();
        let expression = self.real(angle, "rad");
        self.engine
            .quantity_value(&expression, "rad", self.context)?;
        Ok(expression)
    }
    fn critical_ratio(&self, n1: &str, n2: &str) -> Result<BigRational, Error> {
        let n1 = self.index(n1)?;
        let n2 = self.index(n2)?;
        if n1.value <= n2.value {
            return Err(physical());
        }
        model_coordinates::bounded(n2.value / n1.value)
    }
    fn critical(&self, n1: &str, n2: &str) -> Result<String, Error> {
        let ratio = self.critical_ratio(n1, n2)?;
        if ratio == BigRational::new(1.into(), 2.into()) {
            // asin(1/2) is exactly30 degrees; retain that identity for model children.
            return self.emit(
                &coordinate(BigRational::from_integer(30.into()), true)?,
                "°",
            );
        }
        self.angle(&ratio)
    }
    fn snell_answer(&self, n1: &str, n2: &str, theta: &str, output: &str) -> Result<String, Error> {
        let refraction = self.refraction(n1, n2, theta)?;
        let transmission = matches!(refraction, Refraction::Transmitted(_));
        match output {
            "tir" => Ok((!transmission).to_string()),
            "critical" => Ok(report(&[
                ("critical angle", self.critical(n1, n2)?),
                ("refraction possible", transmission.to_string()),
            ])),
            "conditional" if !transmission => Ok("optics_answer(total internal reflection)".into()),
            _ => match refraction {
                Refraction::Transmitted(angle) => Ok(format!("{angle} in °")),
                Refraction::TotalInternalReflection => Err(physical()),
            },
        }
    }
    fn call(&self, name: &str, arguments: &str, position: ModelPosition) -> Result<String, Error> {
        let args = named_quantities::function_arguments(arguments, false)?;
        let name = name.to_ascii_lowercase();
        let expression = match (name.as_str(), args.as_slice()) {
            ("lens_image_distance", [f, o]) | ("lens_object_distance", [f, o]) => {
                let f = self.length(f)?;
                let other = self.length(o)?;
                self.emit(&self.image(&f, &other)?, "m")
            }
            ("lens_focal_length", [o, i]) => {
                let o = self.length(o)?;
                let i = self.length(i)?;
                self.emit(&self.focal(&o, &i)?, "m")
            }
            ("lens_magnification", [o, i]) => {
                let o = self.length(o)?;
                let i = self.length(i)?;
                self.emit(&self.magnification(&o, &i)?, "1")
            }
            ("snell_angle", [n1, n2, theta]) => match self.refraction(n1, n2, theta)? {
                Refraction::Transmitted(angle) => Ok(angle),
                Refraction::TotalInternalReflection => Err(physical()),
            },
            ("critical_angle", [n1, n2]) => self.critical(n1, n2),
            _ => Err(invalid()),
        }?;
        // Canonical angular functions retain their radians default. Nested calls
        // keep the exact coordinate unit until their enclosing model validates it.
        Ok(
            if position == ModelPosition::Standalone
                && matches!(name.as_str(), "snell_angle" | "critical_angle")
            {
                format!("({expression}) in rad")
            } else {
                expression
            },
        )
    }
}