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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//! Typed quantity and natural-expression composition.
use super::{finance::Finance, syntax, units::Units};
mod registry;
mod standard;
use crate::{Context, Error, Outcome, Plugin, re};
use chrono::TimeZone;
pub use standard::StandardRates;
pub(crate) use standard::standard_comparison_operand;
pub(crate) use standard::standard_grouped_comments;
pub(crate) use standard::standard_temporal_units;
pub struct Compositions {
    pub(super) units: Units,
}
impl Default for Compositions {
    fn default() -> Self {
        Self {
            units: registry::extended(Units::default()),
        }
    }
}
impl Plugin for Compositions {
    fn evaluate(&self, input: &str, context: &Context) -> Outcome {
        // ISO dates contain arithmetic signs. A complete dated clock conversion
        // belongs to Time before those signs can claim it as a typed expression.
        if input
            .get(..10)
            .is_some_and(|date| chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").is_ok())
            && super::time::Time::default()
                .evaluate(input, context)
                .is_some()
        {
            return None;
        }
        if let Some(operators) = super::arithmetic::operators(input)
            && operators.iter().any(|(index, operator)| {
                matches!(operator, '*' | '/')
                    && super::calendar::date(&input[..*index], context).is_some()
            })
        {
            return Some(Err(Error("invalid_expression".into())));
        }
        if let Some((source, target)) = syntax::split_last(input, syntax::CONVERSIONS)
            && matches!(target, "percent" | "percentage" | "%")
            && super::named_quantities::has_function(source)
        {
            return Some(self.quantity_value(source, "1", context).and_then(|value| {
                let percent = value * 100.0;
                if percent.is_finite() {
                    Ok(format!("{}%", crate::number(percent)))
                } else {
                    Err(Error("numeric_overflow".into()))
                }
            }));
        }
        if let Some(c) = re!(r"^(.+) is what % of (.+)$").captures(input)
            && (super::named_quantities::has_function(&c[1])
                || super::named_quantities::has_function(&c[2]))
        {
            return Some((|| {
                let a = self.quantity_value(&c[1], "1", context)?;
                let b = self.quantity_value(&c[2], "1", context)?;
                if b == 0.0 {
                    return Err(Error("division_by_zero".into()));
                }
                let percent = a / b * 100.0;
                if !percent.is_finite() {
                    return Err(Error("numeric_overflow".into()));
                }
                Ok(format!("{}%", crate::number(percent)))
            })());
        }
        if input.contains(" is what % ") || input.ends_with(" as %") {
            return super::percentages::Percentages.evaluate(input, context);
        }
        if let Some((_, target)) = syntax::split_last(input, syntax::CONVERSIONS)
            && matches!(
                target,
                "fraction" | "frac" | "a fraction" | "percent" | "percentage" | "%"
            )
        {
            return None;
        }
        if let Some(c) = re!(r"^(.+) in hours and minutes$").captures(input)
            && let Some(seconds) = super::time::Time::default().seconds(&c[1])
        {
            return Some(Ok(super::time::span(seconds, 3600.0)));
        }
        let input = self.normalize_expression(input);
        let input = input.as_str();
        if let Some(c) = re!(r"(?i)^convert (.+)$").captures(input) {
            let expression = self.prepare(&c[1], context, 0);
            return Some(expression.and_then(|s| {
                self.calculate(&s, context).unwrap_or_else(|| {
                    Finance
                        .evaluate(&s, context)
                        .unwrap_or_else(|| Err(Error("invalid_expression".into())))
                })
            }));
        }
        if let Some(c) = re!(r"(?i)^([a-z]{3}) from (.+)$").captures(input) {
            return Finance.evaluate(&format!("{} to {}", &c[2], &c[1]), context);
        }
        if !input.contains('/')
            && (!re!(r" (?:for|over|during|until|till|between) ").is_match(input)
                || re!(r"^(?:(?:days?|weeks?|months?|years?)(?: and (?:days?|weeks?|months?|years?))?|workdays?|weekdays?|business days?|duration) (?:between|from|until|till) ")
                    .is_match(input))
            && let Some(result) = super::calendar::Calendar.evaluate_expression(input, context)
        {
            return Some(result);
        }
        let has_quantity = re!(r"[a-zA-Z]+|[$€£¥]").find_iter(input).any(|m| {
            self_unit(&self.units, m.as_str()) || matches!(m.as_str(), "$" | "€" | "£" | "¥")
        });
        // The extended evaluator also owns complete scalar expressions, including
        // scientific literals outside the standard decimal engine's exponent range.
        let scalar_expression = re!(r"^[0-9eE.,\s()+*/^−-]+$").is_match(input);
        let typed_arithmetic = scalar_expression
            || super::named_quantities::has_function(input)
            || syntax::split_last(input, syntax::CONVERSIONS).is_some_and(|(source, target)| {
                self_unit(&self.units, target)
                    && super::named_quantities::recognizes_quantity(source, &self.units, context)
            })
            || has_quantity
                && (input.contains(['*', '+', '-', '(']) || syntax::ungroup(input) != input);
        if let Some((unit, _)) = syntax::split_last(input, &[" until ", " till "])
            && self.units.unit(unit).is_some()
        {
            return None;
        }
        if !input.contains(['/', '·', '⋅'])
            && !typed_arithmetic
            && !re!(r" (?:for|over|during|until|till) ").is_match(input)
        {
            // A standard fallback must not discard unknown grouped operands. Valid
            // extended quantities above are owned by the complete typed parser.
            return standard_grouped_comments(input)
                .map(|_| Err(Error("invalid_expression".into())));
        }
        if let Some((distance, speed)) = syntax::split_last(input, &[" in "])
            && let Some(a) = self.units.quantity(distance)
            && let Some(b) = self.units.quantity(speed)
            && a.unit.dimension == [1, 0, 0, 0, 0, 0, 0, 0]
            && b.unit.dimension == [1, 0, -1, 0, 0, 0, 0, 0]
        {
            if b.base == 0.0 {
                return Some(Err(Error("division_by_zero".into())));
            }
            return Some(Ok(super::time::span(a.base / b.base, 3600.0)));
        }
        match self.prepare(input, context, 0) {
            Ok(expression) => self.calculate(&expression, context),
            Err(error) => Some(Err(error)),
        }
    }
}
impl Compositions {
    pub(crate) fn quantity_order(
        &self,
        left: &str,
        right: &str,
        context: &Context,
    ) -> Result<std::cmp::Ordering, Error> {
        let left = self.prepare(&self.normalize_expression(left), context, 0)?;
        let right = self.prepare(&self.normalize_expression(right), context, 0)?;
        super::named_quantities::quantity_order(&left, &right, &self.units, context)
    }

    /// Read a typed role in reference-unit coordinates; the normal evaluator owns arithmetic.
    pub(crate) fn quantity_value(
        &self,
        input: &str,
        reference: &str,
        context: &Context,
    ) -> Result<f64, Error> {
        let expression = self.prepare(&self.normalize_expression(input), context, 0)?;
        super::named_quantities::quantity_value(&expression, reference, &self.units, context)
    }

    pub(crate) fn evaluate_money(&self, input: &str, context: &Context) -> Result<String, Error> {
        let expression = self.prepare(&self.normalize_expression(input), context, 0)?;
        super::named_quantities::validate_money(&expression, &self.units, context)?;
        self.calculate(&expression, context)
            .ok_or_else(|| Error("invalid_expression".into()))?
    }

    fn normalize_expression(&self, input: &str) -> String {
        let input = syntax::word_operators(&input.split_whitespace().collect::<Vec<_>>().join(" "))
            .replace("work hours", "hours")
            .replace("work hour", "hour")
            .replace(" per ", " / ")
            .replace(" starting at ", " from ")
            .replace(" starting ", " from ")
            .replace(" beginning ", " from ");
        normalize_unit_powers(&input, &self.units)
    }

    fn calculate(&self, expression: &str, context: &Context) -> Outcome {
        let named = super::named_quantities::recognizes_expression(expression)
            || re!(r"[a-zA-Z]+")
                .find_iter(expression)
                .any(|word| super::named_quantities::extended_count(word.as_str()));
        let result = super::named_quantities::evaluate_any(expression, &self.units, context);
        if !named && matches!(&result, Some(Err(error)) if error.0 == "division_by_zero") {
            return Some(Ok("Error: ∞".into()));
        }
        if !named && matches!(&result, Some(Err(error)) if error.0 == "unsupported_compound_unit") {
            return self
                .units
                .evaluate(expression, context)
                .filter(|result| result.is_ok());
        }
        result
    }

    fn prepare(&self, input: &str, context: &Context, depth: usize) -> Result<String, Error> {
        if depth > 64 {
            return Err(Error("expression_too_deep".into()));
        }
        let input = input.trim();
        if input.ends_with(" until") || input.ends_with(" till") {
            return Err(Error("invalid_endpoint".into()));
        }
        if let Some(endpoint) = input
            .strip_prefix("until ")
            .or_else(|| input.strip_prefix("till "))
        {
            return Ok(format!(
                "{} seconds",
                endpoint_seconds(syntax::ungroup(endpoint), context)?
            ));
        }
        if super::calendar::date(input, context).is_some()
            || super::named_quantities::recognizes_quantity(input, &self.units, context)
            || input.starts_with(char::is_alphabetic) && self_unit(&self.units, input)
        {
            return Ok(input.into());
        }
        let inner = syntax::ungroup(input);
        if inner != input {
            return Ok(format!("({})", self.prepare(inner, context, depth + 1)?));
        }
        if let Some((source, target)) = syntax::split_last(input, syntax::CONVERSIONS)
            && self_unit(&self.units, target)
        {
            return Ok(format!(
                "{} in {target}",
                self.prepare(source, context, depth + 1)?
            ));
        }
        if let Some((name, tail)) = input.split_once('(')
            && matches!(
                name,
                "abs" | "min" | "max" | "mean" | "sum" | "square" | "sqrt" | "round"
            )
            && syntax::groups(input)
                .is_some_and(|groups| groups.len() == 1 && groups[0].end + 1 == input.len())
            && let Some(arguments) = tail.strip_suffix(')')
        {
            let arguments = super::named_quantities::function_arguments(
                arguments,
                matches!(name, "abs" | "square" | "sqrt"),
            )?
            .into_iter()
            .map(|argument| self.prepare(argument, context, depth + 1))
            .collect::<Result<Vec<_>, _>>()?;
            return Ok(format!("{name}({})", arguments.join(", ")));
        }
        if let Some((left, right)) = syntax::split_last(input, &[" from "]) {
            if let Some((start, end)) =
                syntax::split_last(right, &[" until ", " till ", " to ", " through "])
            {
                return self.window(left, start, end, context, depth);
            }
            if let Some((rate, end)) = syntax::split_last(left, &[" until ", " till "]) {
                return self.window(rate, right, end, context, depth);
            }
            if let Some((rate, duration)) =
                syntax::split_last(left, &[" for ", " over ", " during "])
            {
                let start = at_offset(context, endpoint_seconds(right, context)?)?;
                return self.accumulate(rate, duration, &start, depth);
            }
            if let Some((start, duration)) = syntax::split_last(right, &[" for "]) {
                let start = at_offset(context, endpoint_seconds(start, context)?)?;
                return self.accumulate(left, duration, &start, depth);
            }
        }
        if let Some((rate, window)) = syntax::split_last(input, &[" between "])
            && let Some((start, end)) = syntax::split_last(window, &[" and "])
        {
            return self.window(rate, start, end, context, depth);
        }
        if let Some((rate, endpoint)) = syntax::split_last(input, &[" until ", " till "]) {
            let seconds = endpoint_seconds(syntax::ungroup(endpoint), context)?;
            let rate = self.prepare(rate, context, depth + 1)?;
            super::named_quantities::validate_rate(&rate, "1 second", &self.units, context)?;
            return Ok(format!("({rate}) * ({seconds} seconds)"));
        }
        if let Some(&(index, operator)) = super::arithmetic::operators(input)
            .ok_or_else(|| Error("invalid_expression".into()))?
            .iter()
            .rev()
            .find(|(index, op)| "+-".contains(*op) && !input[..*index].trim_end().ends_with(','))
        {
            return Ok(format!(
                "{} {operator} {}",
                self.prepare(&input[..index], context, depth + 1)?,
                self.prepare(&input[index + 1..], context, depth + 1)?
            ));
        }
        if let Some((rate, duration)) = syntax::split_last(input, &[" for ", " over ", " during "])
        {
            return self.accumulate(rate, duration, context, depth);
        }
        if let Some((duration, rate)) = syntax::split_last(input, &[" of "])
            && self
                .units
                .quantity(duration)
                .is_some_and(|q| q.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0])
        {
            return Ok(format!(
                "({}) * ({duration})",
                self.prepare(rate, context, depth + 1)?
            ));
        }
        // Lower each group independently so an inner conversion keeps its scope.
        let mut output = String::new();
        let mut start = 0;
        for group in syntax::groups(input).ok_or_else(|| Error("invalid_expression".into()))? {
            output.push_str(&input[start..group.start]);
            output.push_str(&self.prepare(&input[group.clone()], context, depth + 1)?);
            start = group.end;
        }
        output.push_str(&input[start..]);
        Ok(normalize_rate(&output, &self.units))
    }
    fn accumulate(
        &self,
        rate: &str,
        duration: &str,
        context: &Context,
        depth: usize,
    ) -> Result<String, Error> {
        let duration =
            self.prepare(&duration_expression(duration, context)?, context, depth + 1)?;
        super::named_quantities::validate_quantity(&duration, &self.units, context)
            .map_err(|_| Error("invalid_duration".into()))?;
        let rate = self.prepare(rate, context, depth + 1)?;
        super::named_quantities::validate_rate(&rate, &duration, &self.units, context)?;
        Ok(format!("({rate}) * ({duration})"))
    }

    fn window(
        &self,
        rate: &str,
        start: &str,
        end: &str,
        context: &Context,
        depth: usize,
    ) -> Result<String, Error> {
        let start_seconds = endpoint_seconds(start, context)?;
        let end_seconds = if clock_expression(end)
            || end.contains("later")
            || end == "the same local time tomorrow"
        {
            start_seconds + endpoint_seconds(end, &at_offset(context, start_seconds)?)?
        } else {
            endpoint_seconds(end, context)?
        };
        if end_seconds < start_seconds {
            return Err(Error("invalid_interval".into()));
        }
        let rate = rate
            .trim_end_matches(" for the time")
            .trim_end_matches(" for");
        self.accumulate(
            rate,
            &format!("{} seconds", end_seconds - start_seconds),
            context,
            depth,
        )
    }
}

fn normalize_rate(input: &str, units: &Units) -> String {
    for converter in [" in ", " to ", " as ", " into "] {
        if let Some((source, target)) = input.rsplit_once(converter)
            && standard_unit(units, target)
        {
            return format!("{}{converter}{target}", normalize_rate(source, units));
        }
    }
    re!(r"(?:/\s*|\s+per\s+)([a-zA-Z][a-zA-Z ]*)")
        .replace_all(input, |c: &regex::Captures| {
            let unit_text = &c[1];
            let end = syntax::unit_prefix(unit_text, |name| standard_unit(units, name));
            end.map_or_else(
                || c[0].to_string(),
                |end| format!("/1 {}{}", unit_text[..end].trim(), &unit_text[end..]),
            )
        })
        .into_owned()
}

fn self_unit(units: &Units, name: &str) -> bool {
    super::compound_units::factors(name, |part| {
        units.unit(part).is_some()
            || units
                .units
                .iter()
                .any(|unit| unit.symbol.eq_ignore_ascii_case(part))
            || super::named_quantities::recognizes(part)
            || super::named_quantities::extended_count(part)
    })
    .is_some()
}
fn standard_unit(units: &Units, name: &str) -> bool {
    units.unit(name).is_some()
        || name
            .split('/')
            .all(|part| units.unit(part).is_some() || super::named_quantities::recognizes(part))
}

// Clock arithmetic is evaluated before choosing its next occurrence. Thus
// (11am + 2 hours) can mean 1pm today even when 11am itself has passed.
fn clock_expression(input: &str) -> bool {
    let mut input = syntax::ungroup(input);
    for _ in 0..64 {
        if super::time::clock(input).is_some() {
            return true;
        }
        let Some(operators) = super::arithmetic::operators(input) else {
            return false;
        };
        let Some(&(index, _)) = operators.iter().rev().find(|(_, op)| "+-".contains(*op)) else {
            return false;
        };
        if super::time::Time::default()
            .seconds(&input[index + 1..])
            .is_none()
        {
            return false;
        }
        input = syntax::ungroup(&input[..index]);
    }
    false
}
fn at_offset(context: &Context, seconds: f64) -> Result<Context, Error> {
    let now = context
        .now
        .checked_add_signed(chrono::Duration::milliseconds((seconds * 1000.0) as i64))
        .ok_or_else(|| Error("invalid_endpoint".into()))?;
    Ok(Context {
        now,
        ..context.clone()
    })
}
fn local_instant(
    naive: chrono::NaiveDateTime,
    context: &Context,
) -> Result<chrono::DateTime<chrono::Utc>, Error> {
    match context.timezone.from_local_datetime(&naive) {
        chrono::LocalResult::Single(time) => Ok(time.with_timezone(&chrono::Utc)),
        chrono::LocalResult::Ambiguous(_, _) => Err(Error("ambiguous_endpoint".into())),
        chrono::LocalResult::None => Err(Error("nonexistent_endpoint".into())),
    }
}
fn calendar_seconds(count: f64, unit: &str, context: &Context) -> Result<f64, Error> {
    let start = context.now.with_timezone(&context.timezone);
    let day = super::calendar::add(start.date_naive(), count, unit)
        .ok_or_else(|| Error("invalid_duration".into()))?;
    let end = local_instant(day.and_time(start.time()), context)?;
    Ok((end - context.now).num_milliseconds() as f64 / 1000.0)
}
fn duration_expression(input: &str, context: &Context) -> Result<String, Error> {
    let input = input
        .trim_start_matches("the literal next ")
        .trim_start_matches("literal next ")
        .trim_start_matches("the next ")
        .trim_start_matches("next ")
        .trim_start_matches("another ")
        .replace(" elapsed ", " ")
        .replace("half an hour", "30 minutes")
        .replace("half hour", "30 minutes");
    if let Some(c) = re!(r"^(?:([\d.]+) )?calendar (days?|weeks?|months?|years?)$").captures(&input)
    {
        let count = c
            .get(1)
            .map_or(Ok(1.0), |m| m.as_str().parse::<f64>())
            .map_err(|_| Error("invalid_duration".into()))?;
        if count.fract() != 0.0 || count < 0.0 {
            return Err(Error("invalid_duration".into()));
        }
        return Ok(format!(
            "{} seconds",
            calendar_seconds(count, &c[2], context)?
        ));
    }
    Ok(input)
}
fn endpoint_seconds(input: &str, context: &Context) -> Result<f64, Error> {
    let input = syntax::ungroup(input);
    if input == "the same local time tomorrow" {
        return calendar_seconds(1.0, "day", context);
    }
    if let Some(c) = re!(r"^(?:exactly )?(.+) later$").captures(input) {
        let seconds = super::time::Time::default()
            .seconds(&c[1])
            .ok_or_else(|| Error("invalid_endpoint".into()))?;
        return if seconds < 0.0 {
            Err(Error("endpoint_in_past".into()))
        } else {
            Ok(seconds)
        };
    }
    // Choose a bare clock's local date before resolving DST gaps or overlaps.
    if let Some(seconds) = super::time::clock(input) {
        let local = context.now.with_timezone(&context.timezone);
        let clock = chrono::NaiveTime::from_hms_opt(
            (seconds / 3600) as u32,
            (seconds % 3600 / 60) as u32,
            (seconds % 60) as u32,
        )
        .ok_or_else(|| Error("invalid_endpoint".into()))?;
        let date = if clock < local.time() {
            local
                .date_naive()
                .succ_opt()
                .ok_or_else(|| Error("invalid_endpoint".into()))?
        } else {
            local.date_naive()
        };
        let endpoint = local_instant(date.and_time(clock), context)?;
        return Ok((endpoint - context.now).num_milliseconds() as f64 / 1000.0);
    }
    let mut endpoint = resolve_endpoint(input, context, 0)?;
    if clock_expression(input) && endpoint < context.now {
        let day = context
            .now
            .with_timezone(&context.timezone)
            .date_naive()
            .succ_opt()
            .ok_or_else(|| Error("invalid_endpoint".into()))?;
        let next = Context {
            now: local_instant(day.and_hms_opt(0, 0, 0).unwrap(), context)?,
            ..context.clone()
        };
        endpoint = resolve_endpoint(input, &next, 0)?;
    }
    if endpoint < context.now {
        return Err(Error("endpoint_in_past".into()));
    }
    Ok((endpoint - context.now).num_milliseconds() as f64 / 1000.0)
}
pub(crate) fn resolve_endpoint(
    input: &str,
    context: &Context,
    depth: usize,
) -> Result<chrono::DateTime<chrono::Utc>, Error> {
    if depth > 64 {
        return Err(Error("expression_too_deep".into()));
    }
    let input = syntax::ungroup(input)
        .trim()
        .to_lowercase()
        .replace("midnight tonight", "tomorrow at midnight");
    if let Some(&(index, operator)) = super::arithmetic::operators(&input)
        .ok_or_else(|| Error("invalid_endpoint".into()))?
        .iter()
        .rev()
        .find(|(_, op)| "+-".contains(*op))
        && let Some(seconds) = super::time::Time::default().seconds(&input[index + 1..])
    {
        let endpoint = resolve_endpoint(&input[..index], context, depth + 1)?;
        return endpoint
            .checked_add_signed(chrono::Duration::milliseconds(
                (seconds * 1000.0 * if operator == '+' { 1.0 } else { -1.0 }) as i64,
            ))
            .ok_or_else(|| Error("invalid_endpoint".into()));
    }
    let input = re!(r"^(\d{4}-\d{2}-\d{2}) ((?:\d|noon|midnight).+)$").replace(&input, "$1 at $2");
    let input = if let Some(c) = re!(r"^(.+) (today|tomorrow)$").captures(&input) {
        format!("{} at {}", &c[2], &c[1])
    } else {
        input.to_string()
    };
    if input == "now" {
        return Ok(context.now);
    }
    let (date, seconds) = if let Some(seconds) = super::time::clock(&input) {
        (
            context.now.with_timezone(&context.timezone).date_naive(),
            seconds,
        )
    } else {
        let (day, clock) = input.split_once(" at ").unwrap_or((&input, "midnight"));
        (
            super::calendar::date(day, context).ok_or_else(|| Error("invalid_endpoint".into()))?,
            super::time::clock(clock).ok_or_else(|| Error("invalid_endpoint".into()))?,
        )
    };
    let naive = date
        .and_hms_opt(
            (seconds / 3600) as u32,
            (seconds % 3600 / 60) as u32,
            (seconds % 60) as u32,
        )
        .ok_or_else(|| Error("invalid_endpoint".into()))?;
    local_instant(naive, context)
}

pub(super) fn normalize_unit_powers(input: &str, units: &Units) -> String {
    let input = re!(r"\b([a-zA-Z]+)\^([23])\b").replace_all(input, |c: &regex::Captures| {
        let unit = format!("{}{}", &c[1], if &c[2] == "2" { "²" } else { "³" });
        if units.unit(&unit).is_some() {
            unit
        } else {
            c[0].to_string()
        }
    });
    let input = input.as_ref();
    let input =
        re!(r"\b([a-zA-Z]+) (squared|cubed)\b").replace_all(input, |c: &regex::Captures| {
            let unit = format!(
                "{} {}",
                if &c[2] == "squared" {
                    "square"
                } else {
                    "cubic"
                },
                &c[1]
            );
            if units.unit(&unit).is_some() {
                unit
            } else {
                c[0].to_string()
            }
        });
    let input = input.as_ref();
    input.to_string()
}