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
use super::*;
mod lens;
mod refraction;
impl Request<'_> {
    pub(super) fn wording(&self, input: &str) -> Outcome {
        self.lower_wording(input).transpose()
    }

    fn lower_wording(&self, input: &str) -> Result<Option<String>, Error> {
        let input = input
            .trim()
            .trim_end_matches(['.', '?'])
            .replace('−', "-")
            .replace('’', "'");
        if let Some(answer) = self.lens_clauses(&input)? {
            return Ok(Some(answer));
        }
        if let Some(answer) = self.refraction_clauses(&input)? {
            return Ok(Some(answer));
        }
        macro_rules! rule {
            ($pattern:literal, $c:ident, $body:block) => {
                if let Some($c) = re!($pattern).captures(&input) {
                    return ($body).map(Some);
                }
            };
        }
        // Height reports keep a complete requested field list and local targets.
        rule!(
            r"(?i)^a (?:(converging|diverging) )?(?:thin )?lens has (?:focal length\s+|f\s*=\s*)(.+?) and (an object|object distance|do\s*=)\s*(.+?)( in front of it)?; (?:find|calculate|give|report) (.+?) for (?:an object (.+?) tall|a (.+?) object) using (?:the )?(?:stated thin-lens equations|thin-lens equation)(?: and magnification convention where real images have positive image distance)?$",
            c,
            {
                let Some(fields) = lens_fields(&c[6]) else {
                    return Ok(None);
                };
                if c[3].eq_ignore_ascii_case("an object") || c.get(5).is_some() {
                    self.real_object(&c[4])?;
                }
                let height = c.get(7).or_else(|| c.get(8)).ok_or_else(invalid)?;
                self.lens_height_report(
                    &c[2],
                    &c[4],
                    height.as_str(),
                    c.get(1).map_or("", |v| v.as_str()),
                    &fields,
                )
            }
        );
        rule!(
            r"(?i)^a (.+?) focal-length (?:camera )?lens photographs (?:a|an) (.+?) (?:person|object) standing (.+?) from the lens; using the supplied thin-lens model, (?:give|report|calculate) (.+?), with a real inverted image negative in height$",
            c,
            {
                let Some(fields) = lens_fields(&c[4]) else {
                    return Ok(None);
                };
                self.real_object(&c[3])?;
                let f = self.length(&c[1])?;
                let object = self.length(&c[3])?;
                if self.image(&f, &object)?.value.is_negative() {
                    return Err(physical());
                }
                self.lens_height_report(&c[1], &c[3], &c[2], "", &fields)
            }
        );
        rule!(
            r"(?i)^using 1/f\s*=\s*1/do\s*\+\s*1/di and m\s*=\s*-di/do, (?:determine|find|calculate) (.+?) when f is (.+?), do is (.+?), and (?:the )?object height is (.+)$",
            c,
            {
                let Some(fields) = lens_fields(&c[1]) else {
                    return Ok(None);
                };
                self.lens_height_report(&c[2], &c[3], &c[4], "", &fields)
            }
        );
        rule!(
            r"(?i)^a lens forms a virtual image (.+?) from the lens for an object (.+?) away; (?:what|which) signed focal length and image magnification does the thin-lens model imply if virtual image distance is negative$",
            c,
            {
                self.real_object(&c[2])?;
                let image = self.length(&c[1])?;
                if image.value.is_negative() {
                    return Err(physical());
                }
                let signed = coordinate(-image.value, image.authored)?;
                self.lens_inverse_answer(&c[2], &self.emit(&signed, "m")?, "focal", "", true)
            }
        );
        rule!(
            r"(?i)^a (.+?) lens sees an object (.+?) away that is (.+?) tall; (?:calculate|find|report) (.+?) with the thin-lens sign convention$",
            c,
            {
                let Some(fields) = lens_fields(&c[4]) else {
                    return Ok(None);
                };
                self.real_object(&c[2])?;
                self.lens_height_report(&c[1], &c[2], &c[3], "", &fields)
            }
        );
        rule!(
            r"(?i)^for a (?:thin )?lens with focal length (.+?) and an object distance of (.+?), (?:report|find|calculate) (.+?) when the object is (.+?) (?:high|tall)$",
            c,
            {
                let Some(fields) = lens_fields(&c[3]) else {
                    return Ok(None);
                };
                self.lens_height_report(&c[1], &c[2], &c[4], "", &fields)
            }
        );
        rule!(
            r"(?i)^a thin-lens report should include (.+?) for f\s*=\s*(.+?), do\s*=\s*(.+?), and ho\s*=\s*(.+?); use 1/f\s*=\s*1/do\s*\+\s*1/di$",
            c,
            {
                let Some(fields) = lens_fields(&c[1]) else {
                    return Ok(None);
                };
                self.lens_height_report(&c[2], &c[3], &c[4], "", &fields)
            }
        );
        // Both indices are supplied; material names are labels, never constants.
        rule!(
            r"(?i)^(?:light|a ray) (?:travels|goes|passes) from (?:[a-z]+ with (?:refractive )?index\s+|n\s*=\s*)(.+?) into (?:[a-z]+ with (?:refractive )?index\s+|n\s*=\s*)(.+?) at (?:an )?incidence angle (?:of )?(.+?) (?:measured )?from the (normal|surface); (.+)$",
            c,
            {
                if !re!(r"(?i)^(?:(?:report|find|calculate) the transmitted angle from the normal using snell's law|calculate the snell-law result using the stated angle)$").is_match(&c[5]) {
                    return Ok(None);
                }
                self.snell_from_basis(&c[1], &c[2], &c[3], &c[4])
            }
        );
        rule!(
            r"(?i)^a ray (?:goes|travels|passes) from [a-z]+ \(n\s*=\s*(.+?)\) into (?:a |an )?[a-z]+ (?:of|with) n\s*=\s*(.+?) at (.+?) (?:to|from) the (normal|surface); (?:what is its|find the|calculate the) transmitted angle measured from the normal$",
            c,
            { self.snell_from_basis(&c[1], &c[2], &c[3], &c[4]) }
        );
        rule!(
            r"(?i)^a thin (converging|diverging) lens has focal length (.+?) and an object (.+?) away\. find image distance using 1/f\s*=\s*1/do\s*\+\s*1/di$",
            c,
            {
                self.real_object(&c[3])?;
                self.lens_answer(&c[2], &c[3], None, &c[1], "distance")
            }
        );
        rule!(
            r"(?i)^a thin lens has focal length (.+?); an object is (.+?) away\. find magnification using di from 1/f\s*=\s*1/do\s*\+\s*1/di and m\s*=\s*-di/do$",
            c,
            {
                self.real_object(&c[2])?;
                self.lens_answer(&c[1], &c[2], None, "", "magnification")
            }
        );
        rule!(
            r"(?i)^an object (.+?) tall is (.+?) from a (converging|diverging) thin lens of focal length (.+?)\. find signed image distance, magnification, and image height using the thin-lens equation$",
            c,
            {
                self.real_object(&c[2])?;
                self.lens_answer(&c[4], &c[2], Some(&c[1]), &c[3], "report")
            }
        );
        rule!(
            r"(?i)^(?:for a |a )(?:(converging|diverging) )?(?:thin )?lens (?:with|has) f\s*=\s*(.+?) and do\s*=\s*(.+?)(?:,|\.) (?:calculate|find) (signed image distance|image distance|di|di and magnification)(?: (?:from|using) 1/f\s*=\s*1/do\s*\+\s*1/di(?:, retaining the supplied signs)?| using the thin-lens convention m\s*=\s*-di/do)?$",
            c,
            {
                let output = if c[4].eq_ignore_ascii_case("di and magnification") {
                    "report"
                } else {
                    "distance"
                };
                self.lens_answer(
                    &c[2],
                    &c[3],
                    None,
                    c.get(1).map_or("", |v| v.as_str()),
                    output,
                )
            }
        );
        rule!(
            r"(?i)^find image distance for a thin lens given f\s*=\s*(.+?) and do\s*=\s*(.+)$",
            c,
            { self.lens_answer(&c[1], &c[2], None, "", "distance") }
        );
        rule!(
            r"(?i)^a converging lens has f\s*=\s*(.+?), and the real image must be (.+?) from the lens\. find the object distance using 1/f\s*=\s*1/do\s*\+\s*1/di$",
            c,
            {
                let f = self.length(&c[1])?;
                self.focal_kind(&f, "converging")?;
                let image = self.length(&c[2])?;
                if image.value.is_negative() {
                    return Err(physical());
                }
                Ok(format!(
                    "{} in cm",
                    self.emit(&self.image(&f, &image)?, "m")?
                ))
            }
        );
        rule!(
            r"(?i)^an object at (.+?) from a lens with f\s*=\s*(.+?): calculate image distance using the thin-lens equation, and report if no finite image distance exists$",
            c,
            {
                self.real_object(&c[1])?;
                let object = self.length(&c[1])?;
                let f = self.length(&c[2])?;
                if object.value == f.value {
                    Ok("optics_answer(no finite image distance)".into())
                } else {
                    Ok(format!(
                        "{} in m",
                        self.emit(&self.image(&f, &object)?, "m")?
                    ))
                }
            }
        );
        // Explicit supplied equation and sign convention; no other declarations
        // or requested report fields are silently discarded.
        rule!(
            r"(?i)^with the ideal thin-lens model in air, 1/f\s*=\s*1/do\s*\+\s*1/di, and positive distances for real objects and images, find f from do\s*=\s*(.+?) and di\s*=\s*(.+)$",
            c,
            {
                Ok(format!(
                    "{} in cm",
                    self.call(
                        "lens_focal_length",
                        &format!("{},{}", &c[1], &c[2]),
                        ModelPosition::Operand
                    )?
                ))
            }
        );
        rule!(
            r"(?i)^use 1/f\s*=\s*1/do\s*\+\s*1/di for an ideal thin lens in air, with real objects and real images assigned positive distances; if do\s*=\s*(.+?) and di\s*=\s*(.+?), calculate f$",
            c,
            {
                Ok(format!(
                    "{} in cm",
                    self.call(
                        "lens_focal_length",
                        &format!("{},{}", &c[1], &c[2]),
                        ModelPosition::Operand
                    )?
                ))
            }
        );

        rule!(
            r"(?i)^light in material [a-z]+ with refractive index (.+?) hits material [a-z]+ with index (.+?) at (.+?) from the normal\. find the refracted angle using n[₁1]sinθ[₁1]\s*=\s*n[₂2]sinθ[₂2]; use degrees$",
            c,
            { self.snell_answer(&c[1], &c[2], &c[3], "angle") }
        );
        rule!(
            r"(?i)^a ray goes from [a-z]+, n[₁1]\s*=\s*(.+?), into [a-z]+, n[₂2]\s*=\s*(.+?), at (.+?) from the normal\. find the refracted angle by snell's law; use degrees$",
            c,
            { self.snell_answer(&c[1], &c[2], &c[3], "angle") }
        );
        rule!(
            r"(?i)^for n[₁1]\s*=\s*(.+?), n[₂2]\s*=\s*(.+?), and incidence angle (.+?) from the normal, determine whether total internal reflection occurs using snell's law$",
            c,
            { self.snell_answer(&c[1], &c[2], &c[3], "tir") }
        );
        rule!(
            r"(?i)^a ray travels from n\s*=\s*(.+?) into n\s*=\s*(.+?) at (.+?) from the normal\. use snell's law to calculate the refracted angle if transmission is possible; otherwise state that total internal reflection occurs$",
            c,
            { self.snell_answer(&c[1], &c[2], &c[3], "conditional") }
        );
        rule!(
            r"(?i)^a ray in n\s*=\s*(.+?) enters n\s*=\s*(.+?) at incidence (.+?) from the normal\. using snell's law and degrees, calculate the critical angle and determine whether refraction is possible$",
            c,
            { self.snell_answer(&c[1], &c[2], &c[3], "critical") }
        );
        rule!(
            r"(?i)^use snell's law with n[₁1]\s*=\s*(.+?), n[₂2]\s*=\s*(.+?), and θ[₁1]\s*=\s*(.+?) to find θ[₂2]$",
            c,
            { self.snell_answer(&c[1], &c[2], &c[3], "angle") }
        );

        // Complete declarations bind two signed roles; requested goals determine
        // which inverse or report is produced. Additional records remain invalid.
        rule!(
            r"(?i)^(?:a |for a )(?:(converging|diverging) )?(?:thin )?lens (?:has |with )?(?:focal length\s+|f\s*=\s*)(.+?) and (an object|object distance|do\s*=)\s*(.+?)(?: (in front of it|away|forms an image))?[;,.]\s*(?:find|calculate) (.+)$",
            c,
            {
                let Some(goal) = image_goal(&c[6]) else {
                    return Ok(None);
                };
                if c[3].eq_ignore_ascii_case("an object")
                    || c.get(5).is_some_and(|suffix| {
                        suffix.as_str().eq_ignore_ascii_case("in front of it")
                    })
                {
                    self.real_object(&c[4])?;
                }
                self.lens_answer(
                    &c[2],
                    &c[4],
                    None,
                    c.get(1).map_or("", |v| v.as_str()),
                    goal,
                )
            }
        );
        rule!(
            r"(?i)^an object (?:is )?(.+?) from a (?:(converging|diverging) )?(?:thin )?lens with focal length (.+?)[;,.]\s*(?:find|calculate) (.+)$",
            c,
            {
                let Some(goal) = image_goal(&c[4]) else {
                    return Ok(None);
                };
                self.real_object(&c[1])?;
                self.lens_answer(
                    &c[3],
                    &c[1],
                    None,
                    c.get(2).map_or("", |v| v.as_str()),
                    goal,
                )
            }
        );
        rule!(
            r"(?i)^(?:a |for a )(?:(converging|diverging) )?(?:thin )?lens (?:has |with )?(?:focal length\s+|f\s*=\s*)(.+?) and (?:image distance\s+|di\s*=\s*)(.+?)[;,.]\s*(?:find|calculate) (.+)$",
            c,
            {
                let Some(paired) = inverse_goal(&c[4], "object") else {
                    return Ok(None);
                };
                self.lens_inverse_answer(
                    &c[2],
                    &c[3],
                    "object",
                    c.get(1).map_or("", |v| v.as_str()),
                    paired,
                )
            }
        );
        rule!(
            r"(?i)^a (?:(converging|diverging) )?(?:thin )?lens (?:has |with )?(?:object distance\s+|do\s*=\s*)(.+?) and (?:image distance\s+|di\s*=\s*)(.+?)[;,.]\s*(?:find|calculate) (.+)$",
            c,
            {
                let Some(paired) = inverse_goal(&c[4], "focal") else {
                    return Ok(None);
                };
                self.lens_inverse_answer(
                    &c[2],
                    &c[3],
                    "focal",
                    c.get(1).map_or("", |v| v.as_str()),
                    paired,
                )
            }
        );
        rule!(
            r"(?i)^an object (.+?) from a (?:thin )?lens forms an image (?:at|at a distance of) (.+?)[;,.]\s*(?:find|calculate) (.+)$",
            c,
            {
                let Some(paired) = inverse_goal(&c[3], "focal") else {
                    return Ok(None);
                };
                self.real_object(&c[1])?;
                self.lens_inverse_answer(&c[1], &c[2], "focal", "", paired)
            }
        );
        rule!(
            r"(?i)^(?:light (?:travels|goes|passes)|a ray(?: (?:travels|goes|moves))?) (?:from|in) (?:[a-z]+ (?:with )?)?n[₁1]\s*=\s*(.+?) (?:into|to|enters) (?:[a-z]+ (?:with )?)?n[₂2]\s*=\s*(.+?) at (.+?) from the normal[;,.]\s*(?:use snell's law to )?(?:find|calculate|give) (?:the |its )?(?:(?:refracted|outgoing|new) )?angle(?: (?:using|by) snell's law)?$",
            c,
            { self.snell_answer(&c[1], &c[2], &c[3], "angle") }
        );
        rule!(
            r"(?i)^light (?:travels|goes|passes) from (?:[a-z]+ (?:with )?)?n[₁1]\s*=\s*(.+?) (?:into|to) (?:[a-z]+ (?:with )?)?n[₂2]\s*=\s*(.+?); if (?:the )?refracted angle is (.+?) from the normal, (?:find|calculate) (?:the )?incident angle(?: (?:using|by) snell's law)?$",
            c,
            { self.snell_answer(&c[2], &c[1], &c[3], "angle") }
        );
        Ok(None)
    }
    fn real_object(&self, input: &str) -> Result<(), Error> {
        if self.length(input)?.value.is_negative() {
            Err(physical())
        } else {
            Ok(())
        }
    }
}

fn lens_fields(input: &str) -> Option<Vec<(String, String)>> {
    let mut fields = Vec::new();
    for field in re!(r"(?i),\s*(?:and\s+)?|\s+and\s+").split(input) {
        let c = re!(r"(?i)^(?:the )?(?:signed )?(focal length|object distance|image distance|image location|di|image height|height|magnification)(?: in (.+))?$").captures(field.trim())?;
        let label = match c[1].to_ascii_lowercase().as_str() {
            "image location" | "di" => "image distance".into(),
            "height" => "image height".into(),
            label => label.to_owned(),
        };
        if fields.iter().any(|(existing, _)| existing == &label) {
            return None;
        }
        let default = if label == "magnification" { "1" } else { "m" };
        let target = c.get(2).map_or(default, |unit| unit.as_str()).to_owned();
        fields.push((label, target));
    }
    (1..=4).contains(&fields.len()).then_some(fields)
}

fn image_goal(input: &str) -> Option<&'static str> {
    if re!(r"(?i)^(?:the )?(?:finite )?(?:image distance|di)(?: (?:using|from) (?:1/f\s*=\s*1/do\s*\+\s*1/di|the thin[- ]lens equation))?$").is_match(input) {
        Some("distance")
    } else if re!(r"(?i)^(?:image distance|di) and magnification, then report (?:the )?absolute value of magnification as (?:a )?percent$").is_match(input) {
        Some("absolute_report")
    } else if re!(r"(?i)^(?:image distance|di)(?:, then| and(?: then)?) (?:calculate )?(?:magnification|m\s*=\s*-di/do)(?: using m\s*=\s*-di/do)?$").is_match(input) {
        Some("report")
    } else {
        None
    }
}

fn inverse_goal(input: &str, target: &str) -> Option<bool> {
    let c = re!(r"(?i)^(?:its |the )?(object distance|do|focal length|f)( and(?: then)? (?:the )?magnification(?: -di/do)?)?(?: (?:from|using) 1/f\s*=\s*1/do\s*\+\s*1/di)?$").captures(input)?;
    let role = match c[1].to_ascii_lowercase().as_str() {
        "object distance" | "do" => "object",
        _ => "focal",
    };
    (role == target).then_some(c.get(2).is_some())
}