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
//! Supplied constant-property heat models lower to the existing quantity engine.
mod supplied;
mod wording;
use super::{
    compositions::Compositions, compound_units, integer_queries, syntax, units::format_quantity,
};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_traits::Signed;

#[derive(Default)]
pub struct ThermalQueries {
    engine: Compositions,
}
impl Plugin for ThermalQueries {
    fn rewrite_call(
        &self,
        name: &str,
        arguments: &str,
        context: &Context,
        _: ModelPosition,
    ) -> Outcome {
        if !calls().is_match(&format!("{name}(")) {
            return None;
        }
        Some(
            ThermalRequest {
                engine: &self.engine,
                context,
            }
            .call(name, arguments),
        )
    }
    fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
        ThermalRequest {
            engine: &self.engine,
            context,
        }
        .wording(input)
    }
    fn evaluate(&self, input: &str, context: &Context) -> Outcome {
        let input = syntax::ungroup(input);
        if let Some(expression) = input
            .strip_prefix("thermal_specific_heat(")
            .and_then(|s| s.strip_suffix(')'))
        {
            return Some(
                self.engine
                    .quantity_value(expression, "J/(kg*K)", context)
                    .map(|value| format!("{} J/(kg K)", crate::number(value))),
            );
        }
        if let Some(inner) = input
            .strip_prefix("thermal_report(")
            .and_then(|s| s.strip_suffix(')'))
        {
            return Some(self.evaluate_report(inner, context));
        }
        if let Some(expression) = input
            .strip_prefix("thermal_coefficient(")
            .and_then(|s| s.strip_suffix(')'))
        {
            return Some(
                self.engine
                    .quantity_value(expression, "1/K", context)
                    .map(|value| format!("{} per °C", crate::number(value))),
            );
        }
        let fields = input.strip_prefix("thermal_interval(")?.strip_suffix(')')?;
        Some((|| {
            let (expression, target) = fields
                .split_once(';')
                .ok_or_else(|| Error("invalid_expression".into()))?;
            self.format_interval(expression, target, context)
        })())
    }
    fn rewrite(&self, input: &str, context: &Context) -> Outcome {
        let request = ThermalRequest {
            engine: &self.engine,
            context,
        };
        let expression = match syntax::rewrite_groups(input, |s| request.wording(s)) {
            Some(Ok(expression)) => expression,
            Some(Err(error)) => return Some(Err(error)),
            None => input.to_string(),
        };
        match syntax::rewrite_calls(&expression, calls(), |name, arguments| {
            request.call(name.trim(), arguments)
        }) {
            Ok(lowered) if lowered != input => Some(Ok(lowered)),
            Err(error) => Some(Err(error)),
            _ => None,
        }
    }
}
impl ThermalQueries {
    fn format_interval(
        &self,
        expression: &str,
        target: &str,
        context: &Context,
    ) -> Result<String, Error> {
        let target = if target.trim().eq_ignore_ascii_case("kelvins") {
            "K"
        } else {
            target.trim()
        };
        let unit = self
            .engine
            .units
            .unit(target)
            .filter(|u| u.dimension == [0, 0, 0, 1, 0, 0, 0, 0])
            .ok_or_else(|| Error("incompatible_units".into()))?;
        // Interval coordinates scale without any absolute-temperature offset.
        let value = self.engine.quantity_value(expression, "K", context)? / unit.scale;
        Ok(format_quantity(value, &unit))
    }
    fn evaluate_report(&self, inner: &str, context: &Context) -> Result<String, Error> {
        if inner.len() > 4096 {
            return Err(Error("invalid_expression".into()));
        }
        let fields = inner.split(';').collect::<Vec<_>>();
        if !(2..=3).contains(&fields.len()) {
            return Err(Error("invalid_expression".into()));
        }
        let mut output = Vec::new();
        for field in fields {
            let parts = field.split('|').collect::<Vec<_>>();
            let [kind, target, expression] = parts.as_slice() else {
                return Err(Error("invalid_expression".into()));
            };
            let (label, display) = match *kind {
                "temperature" => {
                    self.engine.quantity_value(expression, "K", context)?;
                    let display = self
                        .engine
                        .evaluate(&format!("({expression}) in {target}"), context)
                        .ok_or_else(|| Error("invalid_expression".into()))??;
                    ("temperature", display)
                }
                "energy" => {
                    self.engine
                        .quantity_value(&format!("1 {target}"), "J", context)?;
                    self.engine.quantity_value(expression, "J", context)?;
                    let display = self
                        .engine
                        .evaluate(&format!("({expression}) in {target}"), context)
                        .ok_or_else(|| Error("invalid_expression".into()))??;
                    ("energy", display)
                }
                "change" => (
                    "temperature change",
                    self.format_interval(expression, target, context)?,
                ),
                _ => return Err(Error("invalid_expression".into())),
            };
            output.push(format!("{label}: {display}"));
        }
        Ok(output.join("; "))
    }
}
fn calls() -> &'static regex::Regex {
    re!(r"(?i)\b(?:sensible_heat|latent_heat|thermal_final_temperature|heat_capacity_energy)\s*\(")
}

/// Normalize only roles explicitly supplied to the thermal-expansion model.
/// The binding name (including `delta_T`) carries no temperature semantics.
pub(super) fn supplied_formula_role(
    role: &str,
    value: &str,
    engine: &Compositions,
    context: &Context,
) -> Result<String, Error> {
    let request = ThermalRequest { engine, context };
    match role.trim().to_ascii_lowercase().as_str() {
        "coefficient" => request.coefficient(value),
        "initial length" => request.role(value, "m", false),
        "temperature rise" => {
            let rise = request.rise(value)?;
            let interval = format!("({rise}*(1 K))");
            engine.quantity_value(&interval, "K", context)?;
            Ok(interval)
        }
        _ => Err(Error("invalid_expression".into())),
    }
}

struct ThermalRequest<'a> {
    engine: &'a Compositions,
    context: &'a Context,
}
impl ThermalRequest<'_> {
    fn role(&self, input: &str, unit: &str, positive: bool) -> Result<String, Error> {
        let value = self.engine.quantity_value(input, unit, self.context)?;
        if value < 0.0 || (positive && value == 0.0) {
            return Err(Error("invalid_physical_quantity".into()));
        }
        Ok(format!("({input})"))
    }
    fn exact(&self, expression: &str) -> Result<Option<String>, Error> {
        match integer_queries::ratio_value(expression) {
            Ok((n, d)) => Ok(Some(format!("rational({n},{d})"))),
            Err(e)
                if matches!(
                    e.0.as_str(),
                    "invalid_integer_expression" | "non_rational_expression"
                ) =>
            {
                Ok(None)
            }
            Err(e) => Err(e),
        }
    }
    // Keep authored affine coordinates exact until after their difference.
    fn temperature(&self, input: &str) -> Result<String, Error> {
        self.temperature_coordinate(input, true)
    }
    fn temperature_coordinate(&self, input: &str, absolute: bool) -> Result<String, Error> {
        let mut value = self.engine.quantity_value(input, "K", self.context)?;
        let input = syntax::ungroup(input).trim();
        for (index, _) in input.char_indices() {
            let Some(unit) = self.engine.units.unit(input[index..].trim()) else {
                continue;
            };
            let scalar = input[..index].trim();
            let expression = match unit.symbol.as_str() {
                "°C" if absolute => format!("({scalar})+27315/100"),
                "°F" if absolute => format!("(({scalar})-32)*5/9+27315/100"),
                "°C" => scalar.to_string(),
                "°F" => format!("({scalar})*5/9"),
                "K" => scalar.to_string(),
                _ => continue,
            };
            match integer_queries::ratio_value(&expression) {
                Ok((n, d)) => {
                    if absolute && n.is_negative() {
                        return Err(Error("invalid_physical_quantity".into()));
                    }
                    return Ok(format!("rational({n},{d})"));
                }
                Err(e)
                    if matches!(
                        e.0.as_str(),
                        "invalid_integer_expression" | "non_rational_expression"
                    ) =>
                {
                    if !absolute {
                        value -= unit.offset;
                    }
                    break;
                }
                Err(e) => return Err(e),
            }
        }
        if absolute && value < 0.0 {
            return Err(Error("invalid_physical_quantity".into()));
        }
        Ok(format!("real({value:e})"))
    }
    fn rise(&self, input: &str) -> Result<String, Error> {
        let scalar = self.temperature_coordinate(input, false)?;
        self.role(&scalar, "1", false)
    }
    fn sensible(
        &self,
        mass: &str,
        capacity: &str,
        start: &str,
        end: &str,
    ) -> Result<String, Error> {
        let mass = self.role(mass, "kg", false)?;
        let capacity = self.capacity(capacity, "J/(kg*K)")?;
        let difference = self.difference(start, end)?;
        Ok(format!("({mass}*{capacity}*({difference})*(1 K))"))
    }
    fn latent(&self, mass: &str, heat: &str) -> Result<String, Error> {
        Ok(format!(
            "({}*{})",
            self.role(mass, "kg", false)?,
            self.role(heat, "J/kg", true)?
        ))
    }
    fn final_temperature(
        &self,
        mass: &str,
        capacity: &str,
        start: &str,
        heat: &str,
    ) -> Result<String, Error> {
        let mass = self.role(mass, "kg", true)?;
        let capacity = self.capacity(capacity, "J/(kg*K)")?;
        let start = self.temperature(start)?;
        self.engine.quantity_value(heat, "J", self.context)?;
        let expression = format!("(({start})*(1 K)+({heat})/({mass}*{capacity}))");
        self.role(&expression, "K", false)?;
        Ok(expression)
    }
    fn call(&self, name: &str, arguments: &str) -> Result<String, Error> {
        let ranges = syntax::groups(arguments).ok_or_else(|| Error("invalid_expression".into()))?;
        let mut start = 0;
        let mut args = Vec::new();
        for (index, ch) in arguments.char_indices() {
            if ch == ',' && !ranges.iter().any(|range| range.contains(&index)) {
                args.push(arguments[start..index].trim());
                start = index + 1;
            }
        }
        args.push(arguments[start..].trim());
        match (name.to_ascii_lowercase().as_str(), args.as_slice()) {
            ("sensible_heat", [m, c, a, b]) => self.sensible(m, c, a, b),
            ("latent_heat", [m, l]) => self.latent(m, l),
            ("heat_capacity_energy", [c, a, b]) => self.capacity_energy(c, a, b),
            ("thermal_final_temperature", [m, c, t, q]) => self.final_temperature(m, c, t, q),
            _ => Err(Error("invalid_expression".into())),
        }
    }
    fn directed_heat(
        &self,
        mass: &str,
        capacity: &str,
        start: &str,
        end: &str,
        cooling: bool,
        target: &str,
    ) -> Result<String, Error> {
        let heat = self.sensible(mass, capacity, start, end)?;
        self.direction(start, end, Some(cooling))?;
        Ok(format!(
            "{} in {target}",
            if cooling { format!("-({heat})") } else { heat }
        ))
    }
    fn direction(&self, start: &str, end: &str, cooling: Option<bool>) -> Result<(), Error> {
        if let Some(cooling) = cooling {
            let difference = self.difference(start, end)?;
            let change = self.engine.quantity_value(&difference, "1", self.context)?;
            if (cooling && change > 0.0) || (!cooling && change < 0.0) {
                return Err(Error("invalid_physical_quantity".into()));
            }
        }
        Ok(())
    }
    fn capacity_units(&self, input: &str) -> String {
        compound_units::explicit_products(input, |leaf| self.engine.units.unit(leaf).is_some())
    }
    fn capacity_expression(&self, input: &str) -> String {
        for (index, _) in input.char_indices() {
            let original = input[index..].trim();
            let units = self.capacity_units(original);
            let Some(factors) = compound_units::factors(&units, |leaf| {
                !leaf.contains(['/', '*', '·', '(', ')']) && self.engine.units.unit(leaf).is_some()
            }) else {
                continue;
            };
            if units == original
                && !factors.iter().any(|(leaf, _)| {
                    self.engine
                        .units
                        .unit(leaf)
                        .is_some_and(|u| u.offset != 0.0)
                })
            {
                continue;
            }
            let mut expression = format!("({})", input[..index].trim());
            for (leaf, power) in factors {
                let unit = self.engine.units.unit(&leaf).unwrap();
                let factor = match unit.symbol.as_str() {
                    "°C" => "(1 K)".into(),
                    "°F" => "(rational(5,9)*(1 K))".into(),
                    _ => format!("(1 {leaf})"),
                };
                expression.push_str(&format!("*({factor})^({power})"));
            }
            return expression;
        }
        input.to_string()
    }
    fn capacity(&self, input: &str, reference: &str) -> Result<String, Error> {
        self.role(&self.capacity_expression(input), reference, true)
    }
    fn coefficient(&self, input: &str) -> Result<String, Error> {
        // Only this explicitly named interval coefficient admits a reciprocal
        // Celsius/Fahrenheit degree. Absolute temperatures keep their offsets.
        let degrees = re!(r"(?i)\bdegree (celsius|fahrenheit)\b").replace_all(input, "degrees $1");
        let reciprocal = re!(r"(?i)\s+per\s+").replace(&degrees, " 1/");
        let expression = self.capacity_expression(&reciprocal);
        self.engine
            .quantity_value(&expression, "1/K", self.context)?;
        Ok(format!("({expression})"))
    }
    fn difference(&self, start: &str, end: &str) -> Result<String, Error> {
        let expression = format!(
            "({})-({})",
            self.temperature(end)?,
            self.temperature(start)?
        );
        Ok(self.exact(&expression)?.unwrap_or(expression))
    }
    fn capacity_energy(&self, capacity: &str, start: &str, end: &str) -> Result<String, Error> {
        Ok(format!(
            "({}*({})*(1 K))",
            self.capacity(capacity, "J/K")?,
            self.difference(start, end)?
        ))
    }
    fn interval(&self, scalar: &str, target: &str) -> String {
        format!("thermal_interval(({scalar})*(1 K);{target})")
    }
}