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
//! Supplied practical quantities lower to the existing typed, time and integer engines.
mod conversions;
mod recipes;
mod supplied_conversions;

use super::{
    compositions::Compositions,
    integer_queries::{self, IntegerQueries},
};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;

#[derive(Default)]
pub struct PracticalQueries {
    engine: Compositions,
}
impl Plugin for PracticalQueries {
    fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
        PracticalRequest {
            engine: &self.engine,
            context,
        }
        .lower(input.trim().trim_end_matches(['?', '.']))
    }
    fn rewrite(&self, input: &str, context: &Context) -> Outcome {
        PracticalRequest {
            engine: &self.engine,
            context,
        }
        .lower(input.trim().trim_end_matches(['?', '.']))
    }
    fn evaluate(&self, input: &str, context: &Context) -> Outcome {
        if let Some(result) = recipes::evaluate_positions(&self.engine, input, context) {
            return Some(result);
        }
        if let Some(result) = recipes::evaluate(&self.engine, input, context) {
            return Some(result);
        }
        if let Some(inner) = input
            .strip_prefix("practical_pair(")
            .and_then(|s| s.strip_suffix(')'))
        {
            return Some((|| {
                let (width, height) = inner
                    .split_once(';')
                    .ok_or_else(|| Error("invalid_expression".into()))?;
                self.engine.quantity_value(width, "m", context)?;
                self.engine.quantity_value(height, "m", context)?;
                Ok(format!(
                    "{} × {}",
                    calculate(&self.engine, width, context)?,
                    calculate(&self.engine, height, context)?
                ))
            })());
        }
        if let Some(inner) = input
            .strip_prefix("practical_label(")
            .and_then(|s| s.strip_suffix(')'))
        {
            return Some((|| {
                let (expression, label) = inner
                    .split_once(';')
                    .ok_or_else(|| Error("invalid_expression".into()))?;
                let label = label.trim();
                if !matches!(label, "fps" | "pixels") {
                    return Err(Error("invalid_expression".into()));
                }
                self.engine.quantity_value(expression, "1", context)?;
                Ok(format!(
                    "{} {label}",
                    calculate(&self.engine, expression, context)?
                ))
            })());
        }
        if let Some(inner) = input
            .strip_prefix("practical_ratio(")
            .and_then(|s| s.strip_suffix(')'))
        {
            return Some((|| {
                let (width, height) = inner
                    .split_once(';')
                    .ok_or_else(|| Error("invalid_expression".into()))?;
                let request = PracticalRequest {
                    engine: &self.engine,
                    context,
                };
                request.positive_scalar(width)?;
                request.positive_scalar(height)?;
                IntegerQueries
                    .evaluate(&format!("reduce {width}/{height} to lowest terms"), context)
                    .ok_or_else(|| Error("invalid_expression".into()))?
                    .map(|ratio| ratio.replace('/', ":"))
            })());
        }
        None
    }
}
fn calculate(engine: &Compositions, input: &str, context: &Context) -> Result<String, Error> {
    engine
        .evaluate(input.trim(), context)
        .ok_or_else(|| Error("invalid_expression".into()))?
}
struct PracticalRequest<'a> {
    engine: &'a Compositions,
    context: &'a Context,
}
enum ShareRole {
    Accepted,
    Rejected,
}
impl PracticalRequest<'_> {
    fn quantity(
        &self,
        input: &str,
        reference: &str,
        positive: bool,
        error: &str,
    ) -> Result<String, Error> {
        let input = re!(r"(?i)(\d)-([a-z]+)").replace_all(input.trim(), "$1 $2");
        let value = self
            .engine
            .quantity_value(&input, reference, self.context)?;
        if value < 0.0 || (positive && value == 0.0) {
            return Err(Error(error.into()));
        }
        Ok(format!("({input})"))
    }
    fn positive_scalar(&self, input: &str) -> Result<String, Error> {
        self.quantity(input, "1", true, "invalid_physical_quantity")
    }
    fn accepted_share(&self, input: &str, role: ShareRole) -> Result<String, Error> {
        let input = input.trim();
        let (numerator, denominator) =
            integer_queries::ratio_value(input.strip_suffix('%').unwrap_or(input).trim())?;
        let denominator = if input.ends_with('%') {
            denominator * 100
        } else {
            denominator
        };
        let fraction = BigRational::new(numerator, denominator);
        if fraction < BigRational::from_integer(0.into())
            || fraction > BigRational::from_integer(1.into())
        {
            return Err(Error("invalid_physical_quantity".into()));
        }
        let accepted = match role {
            ShareRole::Accepted => fraction,
            ShareRole::Rejected => BigRational::from_integer(1.into()) - fraction,
        };
        let expression = format!("rational({},{})", accepted.numer(), accepted.denom());
        if expression.len() > 4096 {
            return Err(Error("integer_limit".into()));
        }
        Ok(expression)
    }
    fn transfer(&self, data: &str, rate: &str) -> Result<String, Error> {
        Ok(format!(
            "{} / {} in seconds",
            self.quantity(data, "GB", false, "invalid_physical_quantity")?,
            self.quantity(rate, "GB/s", true, "invalid_rate")?
        ))
    }
    fn frames(&self, duration: &str, rate: &str) -> Result<String, Error> {
        let duration = self.quantity(duration, "seconds", false, "invalid_duration")?;
        self.quantity(rate, "1", true, "invalid_rate")?;
        let seconds = self
            .engine
            .quantity_value(&duration, "seconds", self.context)?;
        self.engine.quantity_value(
            &format!("{duration} / (1 second) * ({rate})"),
            "1",
            self.context,
        )?;
        // Time owns frame rounding and formatting; its standard route is retained.
        Ok(format!("{seconds} seconds at {rate} fps in frames"))
    }
    fn supplied_factor(
        &self,
        source: &str,
        target: &str,
        factor: &str,
        denominator: &str,
    ) -> Result<String, Error> {
        let source = material_quantity(source);
        let c = re!(r"^([+-]?[\d.,]+)\s+(.+)$")
            .captures(source)
            .ok_or_else(|| Error("invalid_expression".into()))?;
        let source_unit = &c[2];
        let denominator_unit = self.engine.units.unit(denominator);
        let factor_quantity = self
            .engine
            .units
            .quantity(factor)
            .ok_or_else(|| Error("invalid_expression".into()))?;
        if factor_quantity.unit.offset != 0.0
            || denominator_unit
                .as_ref()
                .is_some_and(|unit| unit.offset != 0.0)
        {
            return Err(Error("invalid_expression".into()));
        }
        self.quantity(
            factor,
            &factor_quantity.unit.symbol,
            true,
            "invalid_physical_quantity",
        )?;
        if let Some(source_quantity) = self.engine.units.quantity(source) {
            if source_quantity.unit.offset != 0.0 {
                return Err(Error("invalid_expression".into()));
            }
            self.quantity(
                source,
                &source_quantity.unit.symbol,
                false,
                "invalid_physical_quantity",
            )?;
            if denominator_unit
                .as_ref()
                .is_some_and(|u| u.symbol == source_quantity.unit.symbol)
            {
                return Ok(format!(
                    "({source}) / (1 {denominator}) * ({factor}) in {target}"
                ));
            }
            if denominator_unit
                .as_ref()
                .zip(self.engine.units.unit(target))
                .is_some_and(|(a, b)| a.symbol == b.symbol)
            {
                return Ok(format!(
                    "({source}) / ({factor}) * (1 {denominator}) in {target}"
                ));
            }
        } else if source_unit.to_ascii_lowercase().trim_end_matches('s')
            == denominator.to_ascii_lowercase().trim_end_matches('s')
        {
            // A supplied definition binds an otherwise unknown local count (e.g. butter sticks).
            self.quantity(&c[1], "1", false, "invalid_physical_quantity")?;
            return Ok(format!("({}) * ({factor}) in {target}", &c[1]));
        }
        Err(Error("incompatible_units".into()))
    }
    fn lower(&self, s: &str) -> Outcome {
        if let Some(c) = re!(r"(?i)^a machine (?:produces|makes) (.+?) for (.+?), with (.+?) rejected(?:\. using expected good parts\s*=\s*output\s*\*\s*\(1\s*-\s*reject_rate\))?[,.;]\s*how many good parts are expected$").captures(s) {
            return Some((|| {
                let rate = self.quantity(&c[1], "parts/hour", false, "invalid_rate")?;
                let duration = self.quantity(&c[2], "hours", false, "invalid_duration")?;
                let accepted = self.accepted_share(&c[3], ShareRole::Rejected)?;
                let expression = format!("({rate} * {duration} * {accepted}) in parts");
                self.engine.quantity_value(&expression, "parts", self.context)?;
                Ok(expression)
            })());
        }
        if let Some(c) = re!(r"(?i)^the packaging cell makes (.+?) (?:an|per) (hour|minute) for (.+?); quality reports (.+?) yield\. find expected accepted boxes$").captures(s) {
            return Some((|| {
                let rate = self.quantity(&format!("{} / (1 {})", &c[1], &c[2]), "boxes/hour", false, "invalid_rate")?;
                let duration = self.quantity(&c[3], "hours", false, "invalid_duration")?;
                let accepted = self.accepted_share(&c[4], ShareRole::Accepted)?;
                let expression = format!("({rate} * {duration} * {accepted}) in boxes");
                self.engine.quantity_value(&expression, "boxes", self.context)?;
                Ok(expression)
            })());
        }
        if let Some(c) = re!(r"(?i)^a coating head deposits (.+?) for (.+?)\. what volume in (liters?|litres?|L) is deposited if density is (.+)$").captures(s) {
            return Some((|| {
                let rate = self.quantity(&c[1], "kg/minute", false, "invalid_rate")?;
                let duration = self.quantity(&c[2], "minutes", false, "invalid_duration")?;
                let density = self.quantity(&c[4], "kg/L", true, "invalid_physical_quantity")?;
                let expression = format!("({rate} * {duration} / {density}) in {}", &c[3]);
                self.engine.quantity_value(&expression, "L", self.context)?;
                Ok(expression)
            })());
        }
        if let Some(c) = re!(r"(?i)^a 3d printer lays down (.+?) of material per (hour|minute|second) for (.+?); at density (.+?), what mass is deposited$").captures(s) {
            return Some((|| {
                let volume = self.quantity(&c[1], "cm^3", false, "invalid_physical_quantity")?;
                let period = self.quantity(&format!("1 {}", &c[2]), "hours", true, "invalid_duration")?;
                let duration = self.quantity(&c[3], "hours", false, "invalid_duration")?;
                let density = self.quantity(&c[4], "g/cm^3", true, "invalid_physical_quantity")?;
                let expression = format!("({volume} / {period} * {duration} * {density}) in g");
                self.engine.quantity_value(&expression, "g", self.context)?;
                Ok(expression)
            })());
        }
        if let Some(result) = self.conversions(s) {
            return Some(result);
        }
        if let Some(result) = self.recipes(s) {
            return Some(result);
        }
        if let Some(c) = re!(r"(?i)^a tank initially holds (.+?) and drains at (.+?) for (.+?), then receives (.+?); how many liters remain$").captures(s) {
            return Some((|| {
                let initial = self.quantity(&c[1], "L", false, "invalid_physical_quantity")?;
                let rate = self.quantity(&c[2], "L/min", false, "invalid_rate")?;
                let duration = self.quantity(&c[3], "minutes", false, "invalid_duration")?;
                let received = self.quantity(&c[4], "L", false, "invalid_physical_quantity")?;
                Ok(format!("({initial} - {rate} * {duration} + {received}) in L"))
            })());
        }
        if let Some(c) = re!(r"(?i)^a printer produces (.+?) for (.+?), pauses (.+?), then produces (.+?) for (.+?); how many pages does it print in total$").captures(s) {
            return Some((|| {
                let first_rate = self.quantity(&c[1], "pages/minute", false, "invalid_rate")?;
                let first_time = self.quantity(&c[2], "minutes", false, "invalid_duration")?;
                // The pause has no output, but it is still a supplied duration role.
                self.quantity(&c[3], "seconds", false, "invalid_duration")?;
                let second_rate = self.quantity(&c[4], "pages/minute", false, "invalid_rate")?;
                let second_time = self.quantity(&c[5], "minutes", false, "invalid_duration")?;
                Ok(format!("({first_rate} * {first_time} + {second_rate} * {second_time}) in pages"))
            })());
        }
        if let Some(c) = re!(
            r"(?i)^how long (?:does it take to|to) (?:transfer|upload|download|copy) (.+?) at (.+)$"
        )
        .captures(s)
        {
            return Some(self.transfer(&c[1], &c[2]));
        }
        if let Some(c) =
            re!(r"(?i)^at (.+?), how long to (?:transfer|upload|download|copy) (.+)$").captures(s)
        {
            return Some(self.transfer(&c[2], &c[1]));
        }
        if let Some(c) = re!(
            r"(?i)^a (.+?) file takes (.+?) to (?:download|upload|transfer); what was the average speed in (.+)$"
        )
        .captures(s)
        {
            return Some((|| {
                let data = self.quantity(&c[1], "GB", false, "invalid_physical_quantity")?;
                let duration = self.quantity(&c[2], "seconds", true, "invalid_duration")?;
                Ok(format!("{data} / {duration} in {}", &c[3]))
            })());
        }
        if let Some(c) = re!(r"(?i)^how much data can i transfer in (.+?) at (.+)$").captures(s) {
            return Some((|| {
                Ok(format!(
                    "{} * {} in GB",
                    self.quantity(&c[1], "seconds", false, "invalid_duration")?,
                    self.quantity(&c[2], "GB/s", true, "invalid_rate")?
                ))
            })());
        }
        if let Some(c) = re!(
            r"(?i)^at ([+-]?[\d.]+)[×x] playback, how much of a (.+?) movie can i watch in (.+)$"
        )
        .captures(s)
        {
            return Some((|| {
                let movie = self.quantity(&c[2], "seconds", false, "invalid_duration")?;
                let work = self.quantity(&c[3], "seconds", false, "invalid_duration")?;
                self.quantity(&c[1], "1", false, "invalid_rate")?;
                Ok(format!("min({movie}, {work} * ({})) in minutes", &c[1]))
            })());
        }
        if let Some(c) = re!(
            r"(?i)^a (.+?) (?:tutorial|film|clip|episode|video) (?:played|plays) at ([+-]?[\d.]+)[×x], rounded to the nearest second$"
        )
        .captures(s)
        {
            return Some((|| {
                let duration = self.quantity(&c[1], "seconds", false, "invalid_duration")?;
                let speed = self.quantity(&c[2], "1", true, "invalid_rate")?;
                Ok(format!("round({duration} / {speed}, 1 second) in seconds"))
            })());
        }
        if let Some(c) =
            re!(r"(?i)^how many frames are in a (.+?) video at ([+-]?[\d.]+) fps$").captures(s)
        {
            return Some(self.frames(&c[1], &c[2]));
        }
        if let Some(c) = re!(
            r"(?i)^a ([+-]?[\d.]+) fps (?:clip|recording) lasts (.+?); (?:estimate its frame count to the nearest whole frame|how many frames)$"
        )
        .captures(s)
        {
            return Some(self.frames(&c[2], &c[1]));
        }
        if let Some(c) =
            re!(r"(?i)^how many frames per second is (.+?) frames per (.+)$").captures(s)
        {
            return Some((|| {
                self.quantity(&c[1], "1", false, "invalid_physical_quantity")?;
                let period =
                    self.quantity(&format!("1 {}", &c[2]), "seconds", true, "invalid_duration")?;
                Ok(format!(
                    "practical_label(({}) / {period} * (1 second); fps)",
                    &c[1]
                ))
            })());
        }
        if let Some(c) = re!(
            r"(?i)^a ([+-]?[\d.]+)[×x]([+-]?[\d.]+) image scaled to ([+-]?[\d.]+) pixels wide becomes how many pixels tall$"
        )
        .captures(s)
        {
            return Some((|| {
                for value in [&c[1], &c[2], &c[3]] { self.positive_scalar(value)?; }
                Ok(format!("practical_label(({}) * ({}) / ({}); pixels)", &c[2], &c[3], &c[1]))
            })());
        }
        if let Some(c) = re!(
            r"(?i)^a (.+?) ([+-]?[\d.]+):([+-]?[\d.]+) screen: find its width and height in (.+)$"
        )
        .captures(s)
        {
            return Some((|| {
                let diagonal = self.quantity(&c[1], "m", true, "invalid_physical_quantity")?;
                for value in [&c[2], &c[3]] {
                    self.positive_scalar(value)?;
                }
                Ok(format!(
                    "practical_pair({diagonal} * ({}) / sqrt(square({}) + square({})) in {}; {diagonal} * ({}) / sqrt(square({}) + square({})) in {})",
                    &c[2], &c[2], &c[3], &c[4], &c[3], &c[2], &c[3], &c[4]
                ))
            })());
        }
        if let Some(c) = re!(
            r"(?i)^convert a ([+-]?[\d.]+)[×x]([+-]?[\d.]+) display's aspect ratio to a simplified ratio$"
        )
        .captures(s)
        {
            return Some((|| {
                self.positive_scalar(&c[1])?;
                self.positive_scalar(&c[2])?;
                Ok(format!("practical_ratio({}; {})", &c[1], &c[2]))
            })());
        }
        if let Some(c) = re!(r"(?i)^convert (.+?) to (.+?) using (.+?) = (.+)$").captures(s) {
            // Currency rate definitions and other bindings belong to their existing owners.
            let definition = self.engine.units.quantity(&c[3])?;
            let supplied = self.engine.units.quantity(&c[4])?;
            return Some((|| {
                if definition.unit.dimension != supplied.unit.dimension {
                    return Err(Error("incompatible_units".into()));
                }
                self.quantity(
                    &c[3],
                    &definition.unit.symbol,
                    true,
                    "invalid_physical_quantity",
                )?;
                if definition.unit.offset != 0.0 || supplied.unit.offset != 0.0 {
                    return Err(Error("invalid_expression".into()));
                }
                self.quantity(
                    &c[4],
                    &supplied.unit.symbol,
                    true,
                    "invalid_physical_quantity",
                )?;
                let source = bind_cup(&c[1], &definition.unit.symbol);
                let target_name = bind_cup(&c[2], &definition.unit.symbol);
                let source_quantity = self
                    .engine
                    .units
                    .quantity(&source)
                    .ok_or_else(|| Error("invalid_expression".into()))?;
                self.quantity(
                    &source,
                    &source_quantity.unit.symbol,
                    false,
                    "invalid_physical_quantity",
                )?;
                let target = self
                    .engine
                    .units
                    .unit(&target_name)
                    .ok_or_else(|| Error("invalid_expression".into()))?;
                match (
                    source_quantity.unit.symbol == definition.unit.symbol,
                    target.symbol == definition.unit.symbol,
                ) {
                    (true, false) => Ok(format!(
                        "({source}) / ({}) * ({}) in {target_name}",
                        &c[3], &c[4]
                    )),
                    (false, true) => Ok(format!(
                        "({source}) / ({}) * ({}) in {target_name}",
                        &c[4], &c[3]
                    )),
                    _ => Ok(format!("({source}) in {target_name}")),
                }
            })());
        }
        if let Some(c) =
            re!(r"(?i)^convert (.+?) to (.+?) (?:using|assuming) (.+?) per (.+)$").captures(s)
        {
            self.engine.units.quantity(&c[3])?;
            return Some(self.supplied_factor(&c[1], &c[2], &c[3], &c[4]));
        }
        None
    }
}
fn material_quantity(input: &str) -> &str {
    if let Some(c) = re!(r"(?i)^(.+?) of [a-z]+$").captures(input) {
        return c.get(1).unwrap().as_str();
    }
    if let Some(c) =
        re!(r"(?i)^(.+? (?:grams?|g|kilograms?|kg|ounces?|oz|pounds?|lb)) [a-z]+$").captures(input)
    {
        return c.get(1).unwrap().as_str();
    }
    input
}

// An explicit local US-cup definition disambiguates either unqualified cup slot.
fn bind_cup(value: &str, declared: &str) -> String {
    if declared == "US cup" {
        re!(r"(?i)^(?:([+-]?[\d.,]+(?:e[+-]?\d+)?|one)\s+)?cups?$")
            .replace(value.trim(), "$1 US cup")
            .trim()
            .to_string()
    } else {
        value.to_string()
    }
}