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
//! Supplied chemistry data lowers to the existing dimensional expression engine.
use super::compositions::Compositions;
use super::model_coordinates;
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_traits::{Signed, ToPrimitive, Zero};

fn encoded_name(name: &str) -> String {
    name.as_bytes()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect::<Vec<_>>()
        .join("")
}

fn decoded_name(encoded: &str) -> Result<String, Error> {
    if encoded.is_empty() || !encoded.is_ascii() || !encoded.len().is_multiple_of(2) {
        return Err(Error("invalid_expression".into()));
    }
    let bytes = encoded
        .as_bytes()
        .as_chunks::<2>()
        .0
        .iter()
        .map(|pair| {
            let pair = std::str::from_utf8(pair).map_err(|_| Error("invalid_expression".into()))?;
            u8::from_str_radix(pair, 16).map_err(|_| Error("invalid_expression".into()))
        })
        .collect::<Result<Vec<_>, _>>()?;
    let name = String::from_utf8(bytes).map_err(|_| Error("invalid_expression".into()))?;
    if !re!(r"^[A-Za-z][A-Za-z0-9_]*$").is_match(&name) {
        return Err(Error("invalid_expression".into()));
    }
    Ok(name)
}

fn mole_coordinate(coordinate: &model_coordinates::Coordinate) -> Result<String, Error> {
    if coordinate.authored {
        return Ok(format!(
            "(rational({},{}) mol)",
            coordinate.value.numer(),
            coordinate.value.denom()
        ));
    }
    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}) mol)"))
}

#[derive(Default)]
pub struct Chemistry {
    engine: Compositions,
}
impl Plugin for Chemistry {
    fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
        ChemistryRequest {
            engine: &self.engine,
            context,
        }
        .lower(input.trim().trim_end_matches(['?', '.']))
    }
    fn rewrite(&self, input: &str, context: &Context) -> Outcome {
        let request = ChemistryRequest {
            engine: &self.engine,
            context,
        };
        super::syntax::rewrite_groups(input, |part| {
            request.lower(part.trim().trim_end_matches(['?', '.']))
        })
    }
    fn evaluate(&self, input: &str, context: &Context) -> Outcome {
        let input = super::syntax::ungroup(input);
        if let Some(inner) = input
            .strip_prefix("chemistry_limit_report(")
            .and_then(|value| value.strip_suffix(')'))
        {
            return Some((|| {
                if inner.len() > 4096 {
                    return Err(Error("invalid_expression".into()));
                }
                let parts = inner.split(';').collect::<Vec<_>>();
                let [first, second, limiting, expression] = parts.as_slice() else {
                    return Err(Error("invalid_expression".into()));
                };
                let first = decoded_name(first)?;
                let second = decoded_name(second)?;
                if first.eq_ignore_ascii_case(&second) {
                    return Err(Error("invalid_expression".into()));
                }
                let label = match *limiting {
                    "first" => format!("limiting reactant: {first}"),
                    "second" => format!("limiting reactant: {second}"),
                    "both" => format!("limiting reactants: {first}, {second}"),
                    _ => return Err(Error("invalid_expression".into())),
                };
                if self.engine.quantity_value(expression, "mol", context)? < 0.0 {
                    return Err(Error("invalid_physical_quantity".into()));
                }
                let product = self
                    .engine
                    .evaluate(&format!("({expression}) in mol"), context)
                    .ok_or_else(|| Error("invalid_expression".into()))??;
                Ok(format!("{label}; product amount: {product}"))
            })());
        }
        let inner = input
            .strip_prefix("chemistry_quantity_pair(")?
            .strip_suffix(')')?;
        Some((|| {
            if inner.len() > 4096 {
                return Err(Error("invalid_expression".into()));
            }
            let parts = inner.split(';').collect::<Vec<_>>();
            let [reference, expression, first, second] = parts.as_slice() else {
                return Err(Error("invalid_expression".into()));
            };
            let label = match *reference {
                "L" => "volume",
                "g" => "mass",
                _ => return Err(Error("invalid_expression".into())),
            };
            self.engine.quantity_value(expression, reference, context)?;
            let mut fields = Vec::new();
            for target in [*first, *second] {
                self.engine
                    .quantity_value(&format!("1 {target}"), reference, context)?;
                let display = self
                    .engine
                    .evaluate(&format!("({expression}) in {target}"), context)
                    .ok_or_else(|| Error("invalid_expression".into()))??;
                fields.push(format!("{label}: {display}"));
            }
            Ok(fields.join("; "))
        })())
    }
}
struct ChemistryRequest<'a> {
    engine: &'a Compositions,
    context: &'a Context,
}
impl ChemistryRequest<'_> {
    // M is a concentration abbreviation only in a chemically typed field.
    fn quantity(&self, value: &str, unit: &str, positive: bool) -> Result<String, Error> {
        let value = if unit == "mol/L" {
            re!(r"\bM$").replace(value.trim(), "mol/L").into_owned()
        } else {
            value.trim().to_string()
        };
        let magnitude = self.engine.quantity_value(&value, unit, self.context)?;
        if magnitude < 0.0 || (positive && magnitude == 0.0) {
            return Err(Error("invalid_physical_quantity".into()));
        }
        Ok(format!("({value})"))
    }
    fn product(
        &self,
        a: &str,
        a_unit: &str,
        b: &str,
        b_unit: &str,
        target: &str,
    ) -> Result<String, Error> {
        Ok(format!(
            "{} * {} in {target}",
            self.quantity(a, a_unit, false)?,
            self.quantity(b, b_unit, false)?
        ))
    }
    fn quantity_pair(
        &self,
        expression: &str,
        reference: &str,
        first: &str,
        second: &str,
    ) -> Result<String, Error> {
        self.engine
            .quantity_value(expression, reference, self.context)?;
        let targets = [first, second]
            .map(|target| {
                let unit = self
                    .engine
                    .units
                    .unit(target)
                    .ok_or_else(|| Error("incompatible_units".into()))?;
                self.engine.quantity_value(
                    &format!("1 {}", unit.symbol),
                    reference,
                    self.context,
                )?;
                Ok(unit.symbol)
            })
            .into_iter()
            .collect::<Result<Vec<_>, Error>>()?;
        Ok(format!(
            "chemistry_quantity_pair({reference};{expression};{};{})",
            targets[0], targets[1]
        ))
    }
    fn ratio(
        &self,
        a: &str,
        a_unit: &str,
        b: &str,
        b_unit: &str,
        target: &str,
    ) -> Result<String, Error> {
        Ok(format!(
            "{} / {} in {target}",
            self.quantity(a, a_unit, false)?,
            self.quantity(b, b_unit, true)?
        ))
    }
    fn dilute(
        &self,
        concentration: &str,
        aliquot: &str,
        final_volume: &str,
    ) -> Result<String, Error> {
        let c = self.quantity(concentration, "mol/L", false)?;
        let a = self.quantity(aliquot, "L", true)?;
        let v = self.quantity(final_volume, "L", true)?;
        if self.engine.quantity_value(aliquot, "L", self.context)?
            > self
                .engine
                .quantity_value(final_volume, "L", self.context)?
        {
            return Err(Error("invalid_physical_quantity".into()));
        }
        Ok(format!("{c} * {a} / {v} in mol/L"))
    }
    fn stock(&self, stock: &str, volume: &str, final_concentration: &str) -> Result<String, Error> {
        let c1 = self.quantity(stock, "mol/L", true)?;
        let v2 = self.quantity(volume, "L", true)?;
        let c2 = self.quantity(final_concentration, "mol/L", false)?;
        if self.engine.quantity_value(&c2, "mol/L", self.context)?
            > self.engine.quantity_value(&c1, "mol/L", self.context)?
        {
            return Err(Error("invalid_physical_quantity".into()));
        }
        Ok(format!("{c2} * {v2} / {c1} in mL"))
    }
    fn solution_mass(
        &self,
        volume: &str,
        concentration: &str,
        molar_mass: &str,
    ) -> Result<String, Error> {
        Ok(format!(
            "{} * {} * {} in g",
            self.quantity(volume, "L", true)?,
            self.quantity(concentration, "mol/L", false)?,
            self.quantity(molar_mass, "g/mol", true)?
        ))
    }
    fn gas(
        &self,
        target: &str,
        a: &str,
        b: &str,
        c: &str,
        constant: &str,
    ) -> Result<String, Error> {
        let (a_unit, b_unit, c_unit) = match target {
            "mol" => ("atm", "L", "K"),
            "L" => ("mol", "K", "atm"),
            "K" => ("atm", "L", "mol"),
            _ => ("mol", "K", "L"),
        };
        let a = self.quantity(a, a_unit, true)?;
        let b = self.quantity(b, b_unit, true)?;
        let c = self.quantity(c, c_unit, true)?;
        let r = constant
            .replace(['·', '⋅'], "*")
            .replace("*mol⁻¹*K⁻¹", "/(mol*K)");
        let r = self.quantity(&r, "J/(mol*K)", true)?;
        let (b, c) = if target == "mol" {
            (b, format!("({c} in K)"))
        } else if target != "K" {
            (format!("({b} in K)"), c)
        } else {
            (b, c)
        };
        Ok(match target {
            "mol" => format!("{a} * {b} / ({r} * {c}) in mol"),
            "K" => format!("{a} * {b} / ({r} * {c}) in K"),
            _ => format!("{a} * {r} * {b} / {c} in {target}"),
        })
    }
    fn lower(&self, s: &str) -> Outcome {
        if let Some(c) = re!(r"(?i)^a reaction consumes (.+?) moles? of ([A-Za-z][A-Za-z0-9_]*) per (.+?) moles? of ([A-Za-z][A-Za-z0-9_]*); with (.+?) moles? ([A-Za-z][A-Za-z0-9_]*) and (.+?) moles? ([A-Za-z][A-Za-z0-9_]*) initially and complete reaction, identify limiting reactant and moles of product if each reaction event makes (.+?) moles? product$").captures(s) {
            return Some((|| {
                if c[2].eq_ignore_ascii_case(&c[4])
                    || !c[2].eq_ignore_ascii_case(&c[6])
                    || !c[4].eq_ignore_ascii_case(&c[8]) {
                    return Err(Error("invalid_expression".into()));
                }
                let read = |value: &str| {
                    model_coordinates::read(
                        &format!("({value}) mol"), "mol", self.engine, self.context)
                };
                let a = read(&c[1])?;
                let b = read(&c[3])?;
                let available_a = read(&c[5])?;
                let available_b = read(&c[7])?;
                let product_coefficient = read(&c[9])?;
                if !a.value.is_positive() || !b.value.is_positive()
                    || available_a.value.is_negative() || available_b.value.is_negative()
                    || !product_coefficient.value.is_positive() {
                    return Err(Error("invalid_physical_quantity".into()));
                }
                let bounded = model_coordinates::bounded;
                let extent_a = bounded(&available_a.value / &a.value)?;
                let extent_b = bounded(&available_b.value / &b.value)?;
                let limiting = match extent_a.cmp(&extent_b) {
                    std::cmp::Ordering::Less => "first",
                    std::cmp::Ordering::Greater => "second",
                    std::cmp::Ordering::Equal => "both",
                };
                let product = if a.authored && b.authored && available_a.authored
                    && available_b.authored && product_coefficient.authored {
                    let extent = if extent_a <= extent_b { extent_a } else { extent_b };
                    let amount = bounded(extent * product_coefficient.value)?;
                    format!("rational({},{}) mol", amount.numer(), amount.denom())
                } else {
                    let (available, coefficient) = if limiting == "second" {
                        (&available_b, &b)
                    } else {
                        (&available_a, &a)
                    };
                    format!("{}/{}*{}", mole_coordinate(available)?, mole_coordinate(coefficient)?, mole_coordinate(&product_coefficient)?)
                };
                let report = format!("chemistry_limit_report({};{};{limiting};{product})", encoded_name(&c[2]), encoded_name(&c[4]));
                if report.len() > 4096 {
                    return Err(Error("invalid_expression".into()));
                }
                self.engine.quantity_value(&product, "mol", self.context)?;
                Ok(report)
            })());
        }
        if let Some(c) = re!(r"(?i)^a reaction uses (.+?) moles of reactant per (.+?) moles of product; if (.+?) of reactant is available and its molar mass is (.+?), how many grams of product form assuming the stated ratio and product molar mass (.+)$").captures(s) {
            return Some((|| {
                let reactant_moles = self.quantity(&format!("{} moles", &c[1]), "mol", true)?;
                let product_moles = self.quantity(&format!("{} moles", &c[2]), "mol", true)?;
                let reactant_mass = self.quantity(&c[3], "g", false)?;
                let reactant_molar_mass = self.quantity(&c[4], "g/mol", true)?;
                let product_molar_mass = self.quantity(&c[5], "g/mol", true)?;
                let exact_reactant_moles = model_coordinates::read(&format!("{} moles", &c[1]), "mol", self.engine, self.context)?;
                let exact_product_moles = model_coordinates::read(&format!("{} moles", &c[2]), "mol", self.engine, self.context)?;
                let exact_reactant_mass = model_coordinates::read(&c[3], "g", self.engine, self.context)?;
                let exact_reactant_molar_mass = model_coordinates::read(&c[4], "g/mol", self.engine, self.context)?;
                let exact_product_molar_mass = model_coordinates::read(&c[5], "g/mol", self.engine, self.context)?;
                if exact_reactant_moles.authored && exact_product_moles.authored
                    && exact_reactant_mass.authored && exact_reactant_molar_mass.authored
                    && exact_product_molar_mass.authored {
                    let grams = model_coordinates::bounded(
                        exact_reactant_mass.value * exact_product_moles.value * exact_product_molar_mass.value
                            / (exact_reactant_molar_mass.value * exact_reactant_moles.value),
                    )?;
                    let expression = format!("(rational({},{}) g)", grams.numer(), grams.denom());
                    self.engine.quantity_value(&expression, "g", self.context)?;
                    return Ok(format!("{expression} in g"));
                }
                Ok(format!("{reactant_mass}/{reactant_molar_mass}*{product_moles}/{reactant_moles}*{product_molar_mass} in g"))
            })());
        }
        if let Some(c) = re!(r"(?i)^an? [a-z]+ solution is (.+?); how many (.+?) contain (.+?) moles, and what is that volume in (.+)$").captures(s) {
            return Some((|| {
                let concentration = self.quantity(&c[1], "mol/L", true)?;
                let amount = self.quantity(&format!("{} moles", &c[3]), "mol", false)?;
                let volume = format!("{amount}/{concentration}");
                self.quantity_pair(&volume, "L", &c[2], &c[4])
            })());
        }
        if let Some(c) = re!(r"(?i)^a (?:tank|container|vessel) contains (.+?) of solution at (.+?); how many (.+?) of solute are there, and what is that mass in (.+)$").captures(s) {
            return Some((|| {
                let volume = self.quantity(&c[1], "L", false)?;
                let concentration = self.quantity(&c[2], "g/L", false)?;
                self.quantity_pair(&format!("{volume} * {concentration}"), "g", &c[3], &c[4])
            })());
        }
        if let Some(c) = re!(r"(?i)^a reaction consumes (.+? mol) (\w+) per (.+? mol) (\w+)[.] how many moles of (\w+) correspond to (.+? mol) (\w+)$").captures(s) {
            return Some((|| {
                if c[5] != c[4] || c[7] != c[2] {
                    return Err(Error("invalid_expression".into()));
                }
                Ok(format!("{} * {} / {} in mol", self.quantity(&c[6], "mol", false)?, self.quantity(&c[3], "mol", true)?, self.quantity(&c[1], "mol", true)?))
            })());
        }
        if let Some(c) = re!(r"(?i)^the stoichiometric ratio is (.+? mol) (\w+) to (.+? mol) (\w+)[.] what (\w+) amount is needed for (.+? mol) (\w+)$").captures(s) {
            return Some((|| {
                if c[5] != c[2] || c[7] != c[4] {
                    return Err(Error("invalid_expression".into()));
                }
                Ok(format!("{} * {} / {} in mol", self.quantity(&c[6], "mol", false)?, self.quantity(&c[1], "mol", true)?, self.quantity(&c[3], "mol", true)?))
            })());
        }
        if let Some(c) = re!(r"(?i)^convert density (.+?) to (.+)$").captures(s) {
            return Some(
                self.quantity(&c[1], "g/mL", false)
                    .map(|quantity| format!("{quantity} in {}", &c[2])),
            );
        }
        if let Some(c) =
            re!(r"(?i)^how many moles are in (.+?) of .+? if its molar mass is (.+)$").captures(s)
        {
            return Some(self.ratio(&c[1], "g", &c[2], "g/mol", "mol"));
        }
        if let Some(c) = re!(r"(?i)^(?:find the mass of|how many grams are in) (.+? mol) (?:of )?.+? (?:given a molar mass of|if its molar mass is) (.+)$").captures(s) {
            return Some(self.product(&c[1], "mol", &c[2], "g/mol", "g"));
        }
        if let Some(c) =
            re!(r"(?i)^for (.+? mol) of a substance with molar mass (.+?), find mass in (.+)$")
                .captures(s)
        {
            return Some(self.product(&c[1], "mol", &c[2], "g/mol", &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^what mass of (.+? mol) substance has molar mass (.+)$").captures(s)
        {
            return Some(self.product(&c[1], "mol", &c[2], "g/mol", "g"));
        }
        if let Some(c) = re!(r"(?i)^(?:at (.+?), calculate the molarity of|for) (.+? mol) solute in (.+?) solution(?:, calculate molarity)?$").captures(s) {
            return Some((|| {
                if let Some(temperature) = c.get(1) {
                    self.quantity(temperature.as_str(), "K", true)?;
                }
                self.ratio(&c[2], "mol", &c[3], "L", "mol/L")
            })());
        }
        if let Some(c) = re!(r"(?i)^a solution contains (.+? mol) solute in (.+?)[.] report its concentration in (.+)$").captures(s) {
            return Some(self.ratio(&c[1], "mol", &c[2], "L", &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^i have (.+?) of solute in (.+?) of solution[.] find molarity in (.+)$")
                .captures(s)
        {
            return Some((|| {
                self.engine
                    .quantity_value(&format!("1 {}", &c[3]), "mol/L", self.context)?;
                self.ratio(&c[1], "mol", &c[2], "L", &c[3])
            })());
        }
        if let Some(c) = re!(r"(?i)^dissolve (.+? mol) .+? in enough water to make (.+?) solution[.] what is the molarity$").captures(s) {
            return Some(self.ratio(&c[1], "mol", &c[2], "L", "mol/L"));
        }
        if let Some(c) = re!(r"(?i)^calculate (?:the )?molarity (?:when|from) (.+? mol) solute (?:is in|and) (.+?)(?: solution)?$").captures(s) {
            return Some(self.ratio(&c[1], "mol", &c[2], "L", "mol/L"));
        }
        if let Some(c) = re!(r"(?i)^a solution has (.+?) solute with molar mass (.+?) in (.+?) total solution[.] what is its molarity$").captures(s) {
            return Some((|| Ok(format!("{} / {} / {} in mol/L", self.quantity(&c[1], "g", false)?, self.quantity(&c[2], "g/mol", true)?, self.quantity(&c[3], "L", true)?)))());
        }
        if let Some(c) =
            re!(r"(?i)^how many moles of solute are in (.+?) of a (.+?) solution$").captures(s)
        {
            return Some(self.product(&c[1], "L", &c[2], "mol/L", "mol"));
        }
        if let Some(c) = re!(
            r"(?i)^to prepare (.+?) of (.+?) solution, calculate the amount of solute in moles$"
        )
        .captures(s)
        {
            return Some(self.product(&c[1], "L", &c[2], "mol/L", "mol"));
        }
        if let Some(c) = re!(r"(?i)^what volume of (.+?) stock contains (.+?) solute$").captures(s)
        {
            return Some(self.ratio(&c[2], "mol", &c[1], "mol/L", "L"));
        }
        if let Some(c) =
            re!(r"(?i)^how many liters of (.+?) solution contain (.+?) solute$").captures(s)
        {
            return Some(self.ratio(&c[2], "mol", &c[1], "mol/L", "L"));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) solution provides (.+?) solute[.] what solution volume is required in (.+)$").captures(s) {
            return Some(self.ratio(&c[2], "mol", &c[1], "mol/L", &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^a solution is (.+?)[.] what volume contains (.+?) solute$").captures(s)
        {
            return Some(self.ratio(&c[2], "mol", &c[1], "mol/L", "mL"));
        }
        if let Some(c) = re!(r"(?i)^find the mass of .+? needed to prepare (.+?) of (.+?) solution; use molar mass (.+)$").captures(s) {
            return Some(self.solution_mass(&c[1], &c[2], &c[3]));
        }
        if let Some(c) = re!(r"(?i)^how many grams of .+? \(molar mass (.+?)\) are needed for (.+?) of (.+?) solution$").captures(s) {
            return Some(self.solution_mass(&c[2], &c[3], &c[1]));
        }
        if let Some(c) = re!(
            r"(?i)^what mass of .+? is needed for (.+?) of (.+?) solution\? use molar mass (.+)$"
        )
        .captures(s)
        {
            return Some(self.solution_mass(&c[1], &c[2], &c[3]));
        }
        if let Some(c) = re!(r"(?i)^dilute (.+?) of (.+?) stock to a final volume of (.+?)[.;] (?:what is the final molarity|provide the concentration after dilution)$").captures(s) {
            return Some(self.dilute(&c[2], &c[1], &c[3]));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) portion of (.+?) solution is diluted to (.+?)[.] calculate the resulting concentration$").captures(s) {
            return Some(self.dilute(&c[2], &c[1], &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^a (.+?) solution is diluted from (.+?) to (.+?)[.] find its final molarity$")
                .captures(s)
        {
            return Some(self.dilute(&c[1], &c[2], &c[3]));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) aliquot of (.+?) solution is brought to a final volume of (.+?)[.] find final concentration$").captures(s) {
            return Some(self.dilute(&c[2], &c[1], &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^how much (.+?) acid stock is needed to make (.+?) of (.+?) acid$")
                .captures(s)
        {
            return Some(self.stock(&c[1], &c[2], &c[3]));
        }
        if let Some(c) = re!(r"(?i)^to obtain (.+?) of (.+?) solution from (.+?) stock, what stock volume is required$").captures(s) {
            return Some(self.stock(&c[3], &c[1], &c[2]));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) stock is used to prepare (.+?) of (.+?) solution[.] what volume of stock is needed$").captures(s) {
            return Some(self.stock(&c[1], &c[2], &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^a (.+?) sample has volume (.+?)[.] find its density in (.+)$").captures(s)
        {
            return Some(self.ratio(&c[1], "g", &c[2], "L", &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^a (.+?) object displaces (.+?)[.] calculate its density in (.+)$")
                .captures(s)
        {
            return Some(self.ratio(&c[1], "g", &c[2], "L", &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^a (.+?) material occupies (.+?)[.] calculate density in (.+)$").captures(s)
        {
            return Some(self.ratio(&c[1], "g", &c[2], "L", &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^calculate density if mass is (.+?) and volume is (.+)$").captures(s)
        {
            return Some(self.ratio(&c[1], "g", &c[2], "L", "g/mL"));
        }
        if let Some(c) =
            re!(r"(?i)^what mass corresponds to (.+?) of material with density (.+)$").captures(s)
        {
            return Some(self.product(&c[1], "L", &c[2], "g/mL", "g"));
        }
        if let Some(c) = re!(r"(?i)^a (?:block|sample) (?:has|with) density (.+?) and volume (.+?)[.] what is its mass in (.+)$").captures(s) {
            return Some(self.product(&c[1], "g/mL", &c[2], "L", &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^a sample with density (.+?) occupies (.+?)[.] find its mass in (.+)$")
                .captures(s)
        {
            return Some(self.product(&c[1], "g/mL", &c[2], "L", &c[3]));
        }
        if let Some(c) = re!(
            r"(?i)^a liquid[’']s mass is (.+?) and its density is (.+?)[.] calculate its volume$"
        )
        .captures(s)
        {
            return Some(self.ratio(&c[1], "g", &c[2], "g/mL", "mL"));
        }
        if let Some(c) =
            re!(r"(?i)^find the volume in (.+?) of (.+?) material with density (.+)$").captures(s)
        {
            return Some(self.ratio(&c[2], "g", &c[3], "g/mL", &c[1]));
        }
        if let Some(c) =
            re!(r"(?i)^what volume corresponds to mass (.+?) and density (.+)$").captures(s)
        {
            return Some(self.ratio(&c[1], "g", &c[2], "g/mL", "mL"));
        }
        if let Some(c) =
            re!(r"(?i)^what is the density of (.+?) in (.+?), expressed in (.+)$").captures(s)
        {
            return Some(self.ratio(&c[1], "g", &c[2], "L", &c[3]));
        }
        if let Some(c) = re!(r"(?i)^what amount in moles is present in (.+?) of ideal gas at (.+?) and (.+?), using R = (.+)$").captures(s) {
            return Some(self.gas("mol", &c[2], &c[1], &c[3], &c[4]));
        }
        if let Some(c) = re!(
            r"(?i)^at (.+?), what volume does (.+?) of ideal gas occupy at (.+?)\? use R = (.+)$"
        )
        .captures(s)
        {
            return Some(self.gas("L", &c[2], &c[1], &c[3], &c[4]));
        }
        if let Some(c) = re!(r"(?i)^an ideal gas occupies (.+?) at (.+?) and (.+?)[.] find its amount in moles using R = (.+)$").captures(s) {
            return Some(self.gas("mol", &c[3], &c[1], &c[2], &c[4]));
        }
        if let Some(c) = re!(r"(?i)^what pressure does (.+?) of ideal gas exert in a (.+?) vessel at (.+?)\? take R = (.+)$").captures(s) {
            return Some(self.gas("atm", &c[1], &c[3], &c[2], &c[4]));
        }
        if let Some(c) = re!(r"(?i)^find the temperature of (.+?) of ideal gas at (.+?) in a (.+?) container, using R = (.+)$").captures(s) {
            return Some(self.gas("K", &c[2], &c[3], &c[1], &c[4]));
        }
        if let Some(c) =
            re!(r"(?i)^a gas at (.+?) occupies (.+?) at (.+?)[.] find moles using R = (.+)$")
                .captures(s)
        {
            return Some(self.gas("mol", &c[1], &c[2], &c[3], &c[4]));
        }
        if let Some(c) =
            re!(r"(?i)^what volume will (.+?) ideal gas occupy at (.+?) and (.+?) with R = (.+)$")
                .captures(s)
        {
            return Some(self.gas("L", &c[1], &c[3], &c[2], &c[4]));
        }
        if let Some(c) = re!(r"(?i)^an ideal gas has volume (.+?), pressure (.+?), and temperature (.+?)[.] find moles using R = (.+)$").captures(s) {
            return Some(self.gas("mol", &c[2], &c[1], &c[3], &c[4]));
        }
        if let Some(c) =
            re!(r"(?i)^how many moles occupy (.+?) at (.+?) and (.+?) using R = (.+)$").captures(s)
        {
            return Some(self.gas("mol", &c[2], &c[1], &c[3], &c[4]));
        }
        None
    }
}