calcli 0.4.0

Fast terminal calculator (TUI) with history, variables and engineering helpers
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! The calculator service: the one place that drives evaluation, history and
//! variables, and owns the display settings.
//!
//! It threads the previous answer through the history, re-evaluates the tail
//! when a line is edited or deleted, and applies settings changes (recomputing
//! when a change alters results, such as the angle mode or decimal separator).
//! All values are full-precision `f64`s; rounding lives in
//! [`crate::domain::format`].

use crate::domain::evaluator::Evaluator;
use crate::domain::expression::{self, Statement};
use crate::domain::format::{
    AngleMode, FormatSettings, Notation, format_display, format_plain,
};
use crate::domain::history::{History, HistoryEntry, LineResult};
use crate::domain::quantity::Quantity;
use crate::domain::variables::VariableStore;
use crate::services::eval::{self, eval_expression, reject_name};

/// The outcome of submitting a line, for the caller's status line.
#[derive(Debug, Clone, PartialEq)]
pub struct SubmitOutcome {
    /// The computed value, when the line succeeded.
    pub value: Option<Quantity>,
    /// The error message, when the line failed.
    pub error: Option<String>,
}

/// A non-mutating live preview of the current input, for typed feedback.
#[derive(Debug, Clone, PartialEq)]
pub enum Preview {
    /// Nothing to show (empty input or a `:` command).
    Empty,
    /// The input currently evaluates to this value.
    Value(Quantity),
    /// The input looks unfinished (still being typed); show no warning.
    Incomplete,
    /// The input looks complete but does not parse; show a warning.
    Invalid,
}

/// Orchestrates evaluation, history and variables behind one façade.
pub struct CalcService {
    evaluator: Box<dyn Evaluator>,
    variables: VariableStore,
    history: History,
    settings: FormatSettings,
}

impl CalcService {
    /// Builds a service with the given engine, settings and (possibly restored)
    /// history and variables.
    pub fn new(
        evaluator: Box<dyn Evaluator>,
        settings: FormatSettings,
        history: History,
        variables: VariableStore,
    ) -> Self {
        CalcService {
            evaluator,
            variables,
            history,
            settings,
        }
    }

    /// The current display settings (the source of truth for the settings bar).
    pub fn settings(&self) -> &FormatSettings {
        &self.settings
    }

    /// The calculation history.
    pub fn history(&self) -> &History {
        &self.history
    }

    /// The defined variables.
    pub fn variables(&self) -> &VariableStore {
        &self.variables
    }

    /// Evaluates a new input line and appends it to the history.
    ///
    /// An errored line is still recorded (with its message) so the user can
    /// edit or delete it; its `ans` is `None` for the line below.
    ///
    /// # Examples
    ///
    /// Each line may continue from the previous answer through `ans`:
    ///
    /// ```
    /// use calcli::config::Config;
    /// use calcli::domain::evaluator::MevalEvaluator;
    /// use calcli::domain::history::History;
    /// use calcli::domain::quantity::Quantity;
    /// use calcli::domain::variables::VariableStore;
    /// use calcli::services::CalcService;
    ///
    /// let mut service = CalcService::new(
    ///     Box::new(MevalEvaluator::new()),
    ///     Config::default().format_settings(),
    ///     History::new(100),
    ///     VariableStore::new(),
    /// );
    ///
    /// service.submit("10");
    /// let outcome = service.submit("ans * 3");
    ///
    /// assert_eq!(
    ///     outcome.value.as_ref().map(Quantity::display_value),
    ///     Some(30.0),
    /// );
    /// assert_eq!(service.history().len(), 2);
    /// ```
    pub fn submit(&mut self, input: &str) -> SubmitOutcome {
        let ans = self.history.last_value();
        let (value, error) = self.evaluate_line(input, ans);
        let outcome = SubmitOutcome {
            value: value.clone(),
            error: error.clone(),
        };
        self.history.push(HistoryEntry {
            input: input.to_string(),
            value,
            error,
        });
        outcome
    }

    /// Replaces the input of the entry at `index` and re-evaluates the tail.
    pub fn edit_entry(&mut self, index: usize, new_input: &str) {
        self.history.set_input(index, new_input.to_string());
        self.recompute(index);
    }

    /// Removes the entry at `index` and re-evaluates the tail.
    pub fn delete_entry(&mut self, index: usize) {
        self.history.remove(index);
        self.recompute(index);
    }

    /// Moves the entry at `index` by `delta` positions (clamped) and
    /// re-evaluates from the first affected line. Returns the new index, so the
    /// caller can follow the moved entry with its selection.
    pub fn move_entry(&mut self, index: usize, delta: isize) -> usize {
        let len = self.history.len();
        if len == 0 {
            return 0;
        }
        let target = step_index(index, delta, len);
        if target != index {
            self.history.swap(index, target);
            self.recompute(index.min(target));
        }
        target
    }

    /// Inserts a blank entry at `index` and re-evaluates the tail. The caller
    /// typically edits it immediately.
    pub fn insert_entry(&mut self, index: usize) {
        let blank = HistoryEntry {
            input: String::new(),
            value: None,
            error: None,
        };
        self.history.insert(index, blank);
        self.recompute(index);
    }

    /// Clears the history.
    pub fn clear_history(&mut self) {
        self.history.clear();
    }

    /// Re-evaluates the entire history, regenerating values and errors under
    /// the
    /// current settings. Used on startup so restored entries are consistent
    /// with
    /// the active settings (and with each other).
    pub fn recompute_all(&mut self) {
        self.recompute(0);
    }

    /// Removes every variable.
    pub fn reset_variables(&mut self) {
        self.variables.clear();
    }

    /// Removes a single variable by name.
    pub fn remove_variable(&mut self, name: &str) {
        self.variables.remove(name);
    }

    /// Advances the notation (display only; values are unchanged).
    pub fn cycle_notation(&mut self) {
        self.settings.notation = self.settings.notation.next();
    }

    /// Sets the notation directly (display only), for the `:` commands.
    pub fn set_notation(&mut self, notation: Notation) {
        self.settings.notation = notation;
    }

    /// Sets the angle mode directly, recomputing only when it changes.
    pub fn set_angle_mode(&mut self, angle_mode: AngleMode) {
        if self.settings.angle_mode != angle_mode {
            self.settings.angle_mode = angle_mode;
            self.recompute(0);
        }
    }

    /// Sets the number of fractional digits (display only).
    pub fn set_decimals(&mut self, decimals: usize) {
        self.settings.decimals = decimals;
    }

    /// Toggles the angle mode and recomputes, since trig results change.
    pub fn toggle_angle_mode(&mut self) {
        self.settings.angle_mode = self.settings.angle_mode.toggled();
        self.recompute(0);
    }

    /// Toggles the decimal separator and recomputes, since it changes how input
    /// numbers are parsed.
    pub fn toggle_decimal_separator(&mut self) {
        self.settings.toggle_decimal_separator();
        self.recompute(0);
    }

    /// Toggles whether trailing fractional zeros are dropped (display only, so
    /// no recompute is needed).
    pub fn toggle_trim_trailing_zeros(&mut self) {
        self.settings.trim_trailing_zeros = !self.settings.trim_trailing_zeros;
    }

    /// Sets the thousands group separator used for display. Input parsing is
    /// tolerant of any grouping, so no recompute is needed.
    pub fn set_thousands_separator(&mut self, separator: String) {
        self.settings.thousands_separator = separator;
    }

    /// Renders a quantity for display (rounded, grouped) - for the `Y` copy.
    pub fn format_display(&self, value: &Quantity) -> String {
        format_display(value, &self.settings)
    }

    /// Renders a quantity as a plain, full-precision value - for the `y` copy.
    pub fn format_plain(&self, value: &Quantity) -> String {
        format_plain(value, &self.settings)
    }

    /// Previews the current input without mutating history, variables or `ans`.
    ///
    /// Returns the value when it evaluates, [`Preview::Incomplete`] while the
    /// input still looks like it is being typed (so no warning is shown), and
    /// [`Preview::Invalid`] when a complete-looking input does not parse.
    pub fn preview(&self, input: &str) -> Preview {
        // The comment is not part of the calculation; a comment-only line (or a
        // command) shows no preview.
        let code = expression::strip_comment(input).trim();
        if code.is_empty() || code.starts_with(':') {
            return Preview::Empty;
        }
        match self.preview_value(code) {
            Some(value) => Preview::Value(value),
            None if expression::looks_incomplete(code) => Preview::Incomplete,
            None => Preview::Invalid,
        }
    }

    /// Evaluates the input for the preview, reusing the submit pipeline but
    /// reading (not mutating) the variable store.
    fn preview_value(&self, input: &str) -> Option<Quantity> {
        let ans = self.history.last_value();
        match expression::classify(input) {
            Statement::SaveAns(name) => {
                if reject_name(&name).is_some() {
                    return None;
                }
                ans
            }
            Statement::Assign { name, expr } => {
                if reject_name(&name).is_some() {
                    return None;
                }
                eval_expression(
                    self.evaluator.as_ref(),
                    &self.variables,
                    &self.settings,
                    &expr,
                    ans,
                )
                .ok()
            }
            Statement::Expression(expr) => eval_expression(
                self.evaluator.as_ref(),
                &self.variables,
                &self.settings,
                &expr,
                ans,
            )
            .ok(),
        }
    }

    /// Re-evaluates the history from `start`, threading `ans` and applying
    /// variable assignments in order. Borrows the engine, variables and
    /// settings
    /// disjointly from the history so the closure can mutate the store.
    fn recompute(&mut self, start: usize) {
        let evaluator = self.evaluator.as_ref();
        let variables = &mut self.variables;
        let settings = &self.settings;
        self.history.recompute_from(start, |input, ans| {
            eval::evaluate_line(evaluator, variables, settings, input, ans)
        });
    }

    /// Evaluates a single line against the current engine, variables and
    /// settings (used by [`submit`](Self::submit)).
    fn evaluate_line(
        &mut self,
        input: &str,
        ans: Option<Quantity>,
    ) -> LineResult {
        eval::evaluate_line(
            self.evaluator.as_ref(),
            &mut self.variables,
            &self.settings,
            input,
            ans,
        )
    }
}

/// Steps `index` by `delta` within a list of `len` entries, clamped to its
/// ends. `len` must not be zero.
///
/// `index` and `delta` both cross the API boundary from the UI, so the step is
/// computed with `checked_*`: a plain `index as isize + delta` panics in debug
/// and wraps in release once the values grow past `isize`. Anything that does
/// not fit saturates at the end it was heading for, which is what clamping
/// would have done anyway.
fn step_index(index: usize, delta: isize, len: usize) -> usize {
    let last = len - 1;
    let Ok(current) = isize::try_from(index) else {
        return last;
    };
    let Some(target) = current.checked_add(delta) else {
        return if delta < 0 { 0 } else { last };
    };
    match usize::try_from(target) {
        Ok(target) => target.min(last),
        Err(_) => 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::domain::evaluator::MevalEvaluator;
    use crate::domain::format::{AngleMode, Notation};

    fn settings() -> FormatSettings {
        FormatSettings {
            notation: Notation::Decimal,
            decimals: 3,
            angle_mode: AngleMode::Rad,
            decimal_separator: '.',
            thousands_separator: " ".to_string(),
            trim_trailing_zeros: false,
        }
    }

    fn service() -> CalcService {
        CalcService::new(
            Box::new(MevalEvaluator::new()),
            settings(),
            History::new(100),
            VariableStore::new(),
        )
    }

    fn value_at(service: &CalcService, index: usize) -> Option<f64> {
        service.history().entries()[index]
            .value
            .as_ref()
            .map(Quantity::display_value)
    }

    fn last(service: &CalcService) -> Option<f64> {
        service.history().last_value().map(|q| q.display_value())
    }

    fn var(service: &CalcService, name: &str) -> Option<f64> {
        service.variables().get(name).map(Quantity::display_value)
    }

    fn outval(outcome: &SubmitOutcome) -> Option<f64> {
        outcome.value.as_ref().map(Quantity::display_value)
    }

    /// A dimensionless value preview, for the preview assertions.
    fn val(value: f64) -> Preview {
        Preview::Value(Quantity::dimensionless(value))
    }

    /// `index` and `delta` arrive from the UI, so the step must survive values
    /// a plain `index as isize + delta` would panic or wrap on.
    #[test]
    fn stepping_an_index_clamps_instead_of_overflowing() {
        assert_eq!(step_index(0, -1, 3), 0);
        assert_eq!(step_index(2, 1, 3), 2);
        assert_eq!(step_index(1, 1, 3), 2);
        assert_eq!(step_index(1, -1, 3), 0);
        assert_eq!(step_index(0, isize::MAX, 3), 2);
        assert_eq!(step_index(2, isize::MIN, 3), 0);
        assert_eq!(step_index(usize::MAX, 1, 3), 2);
    }

    /// An empty history has no index to move to, and must not underflow on the
    /// `len - 1` that clamping needs.
    #[test]
    fn moving_an_entry_in_an_empty_history_is_a_no_op() {
        let mut service = service();
        assert_eq!(service.move_entry(0, 1), 0);
        assert_eq!(service.history().len(), 0);
    }

    #[test]
    fn submit_evaluates_and_records_history() {
        let mut service = service();
        let outcome = service.submit("2+3");
        assert_eq!(outval(&outcome), Some(5.0));
        assert_eq!(last(&service), Some(5.0));
    }

    #[test]
    fn ans_continues_from_the_previous_line() {
        let mut service = service();
        service.submit("10");
        service.submit("+5");
        assert_eq!(value_at(&service, 1), Some(15.0));
        service.submit("ans*2");
        assert_eq!(value_at(&service, 2), Some(30.0));
    }

    #[test]
    fn editing_a_line_recomputes_the_chain_below() {
        let mut service = service();
        service.submit("10");
        service.submit("ans+5");
        service.submit("ans*2");
        assert_eq!(value_at(&service, 2), Some(30.0));
        service.edit_entry(0, "20");
        assert_eq!(value_at(&service, 1), Some(25.0));
        assert_eq!(value_at(&service, 2), Some(50.0));
    }

    #[test]
    fn deleting_a_line_recomputes_the_chain_below() {
        let mut service = service();
        service.submit("10");
        service.submit("ans+5");
        service.submit("ans+100");
        service.delete_entry(1);
        // The former third line now follows the first: 10 + 100.
        assert_eq!(value_at(&service, 1), Some(110.0));
    }

    #[test]
    fn save_ans_and_assignment_define_variables() {
        let mut service = service();
        service.submit("7");
        service.submit("=x");
        assert_eq!(var(&service, "x"), Some(7.0));
        service.submit("y = x + 3");
        assert_eq!(var(&service, "y"), Some(10.0));
        service.submit("y*2");
        assert_eq!(last(&service), Some(20.0));
    }

    #[test]
    fn reserved_and_invalid_names_are_rejected() {
        let mut service = service();
        service.submit("5");
        let outcome = service.submit("=pi");
        assert!(outcome.error.is_some());
        let outcome = service.submit("1abc = 3");
        assert!(outcome.error.is_some());
    }

    #[test]
    fn an_errored_line_is_recorded_without_a_value() {
        let mut service = service();
        let outcome = service.submit("2+");
        assert!(outcome.error.is_some());
        assert_eq!(last(&service), None);
    }

    #[test]
    fn toggling_angle_mode_recomputes_history() {
        let mut service = service();
        service.submit("sin(90)");
        // In radians sin(90) is not 1.
        assert!((value_at(&service, 0).unwrap() - 1.0).abs() > 0.1);
        service.toggle_angle_mode();
        assert!((value_at(&service, 0).unwrap() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn toggling_decimal_separator_reparses_history_input() {
        let mut service = service();
        // With '.' decimal, the comma is a thousands separator: 1,5 -> 15.
        service.submit("1,5");
        assert_eq!(value_at(&service, 0), Some(15.0));
        service.toggle_decimal_separator();
        // With ',' decimal, 1,5 -> 1.5.
        assert_eq!(value_at(&service, 0), Some(1.5));
    }

    #[test]
    fn variable_used_before_assignment_recomputes_after_edit() {
        let mut service = service();
        service.submit("a = 2");
        service.submit("a * 10");
        assert_eq!(value_at(&service, 1), Some(20.0));
        service.edit_entry(0, "a = 5");
        assert_eq!(value_at(&service, 1), Some(50.0));
    }

    #[test]
    fn preview_reports_value_incomplete_and_invalid() {
        let mut service = service();
        service.submit("10");
        assert_eq!(service.preview("2+3"), val(5.0));
        assert_eq!(service.preview("ans+5"), val(15.0));
        assert_eq!(service.preview("2+"), Preview::Incomplete);
        assert_eq!(service.preview("2+3)"), Preview::Invalid);
        assert_eq!(service.preview(""), Preview::Empty);
        assert_eq!(service.preview(":d4"), Preview::Empty);
    }

    #[test]
    fn preview_handles_assignments_without_mutating_state() {
        let mut service = service();
        service.submit("7");
        assert_eq!(service.preview("x = ans + 3"), val(10.0));
        // Previewing must not define the variable or add to the history.
        assert!(service.variables().get("x").is_none());
        assert_eq!(service.history().len(), 1);
        // A reserved name is invalid, not a value.
        assert_eq!(service.preview("pi = 3"), Preview::Invalid);
    }

    #[test]
    fn inline_comments_are_ignored_but_kept_in_history() {
        let mut service = service();
        let outcome = service.submit("2+3 # the sum");
        assert_eq!(outval(&outcome), Some(5.0));
        // The full input, including the comment, is stored.
        assert_eq!(service.history().entries()[0].input, "2+3 # the sum");
        // Comments work on assignments too.
        service.submit("x = 5 # a note");
        assert_eq!(var(&service, "x"), Some(5.0));
    }

    #[test]
    fn a_comment_only_line_is_a_note_that_passes_ans_through() {
        let mut service = service();
        service.submit("5");
        let outcome = service.submit("# just a note");
        assert_eq!(outcome.value, None);
        assert_eq!(outcome.error, None);
        assert_eq!(service.history().entries()[1].input, "# just a note");
        // The note does not break the `ans` chain.
        service.submit("ans + 1");
        assert_eq!(value_at(&service, 2), Some(6.0));
    }

    #[test]
    fn moving_an_entry_recomputes_the_ans_chain() {
        let mut service = service();
        service.submit("10");
        service.submit("ans + 5"); // 15
        service.submit("ans * 2"); // 30
        // Move the last line up one: ["10", "ans*2", "ans+5"].
        let new_index = service.move_entry(2, -1);
        assert_eq!(new_index, 1);
        assert_eq!(value_at(&service, 1), Some(20.0)); // ans*2 with ans=10
        assert_eq!(value_at(&service, 2), Some(25.0)); // ans+5 with ans=20
    }

    #[test]
    fn inserting_a_blank_entry_shifts_and_recomputes() {
        let mut service = service();
        service.submit("10");
        service.submit("ans + 5"); // 15
        service.insert_entry(1);
        assert_eq!(service.history().len(), 3);
        assert_eq!(service.history().entries()[1].input, "");
        // The blank note passes ans through, so `ans + 5` is still 15.
        assert_eq!(value_at(&service, 2), Some(15.0));
    }

    #[test]
    fn preview_ignores_comments() {
        let mut service = service();
        service.submit("2");
        assert_eq!(service.preview("# note"), Preview::Empty);
        assert_eq!(service.preview("ans+3 # sum"), val(5.0));
    }

    #[test]
    fn converts_a_quantity_with_the_arrow() {
        let mut service = service();
        let outcome = service.submit("123 MPa -> bar");
        let quantity = outcome.value.unwrap();
        assert_eq!(quantity.unit_symbol(), Some("bar"));
        assert!((quantity.display_value() - 1230.0).abs() < 1e-6);
    }

    #[test]
    fn stores_a_quantity_variable_and_converts_it() {
        let mut service = service();
        service.submit("x = 50 kN");
        assert_eq!(
            service.variables().get("x").unwrap().unit_symbol(),
            Some("kN")
        );
        let outcome = service.submit("x -> N");
        let quantity = outcome.value.unwrap();
        assert_eq!(quantity.unit_symbol(), Some("N"));
        assert!((quantity.display_value() - 50_000.0).abs() < 1e-9);
    }

    #[test]
    fn ans_carries_its_unit_into_a_conversion() {
        let mut service = service();
        service.submit("2 bar");
        let outcome = service.submit("ans -> Pa");
        let quantity = outcome.value.unwrap();
        assert_eq!(quantity.unit_symbol(), Some("Pa"));
        assert!((quantity.display_value() - 200_000.0).abs() < 1e-6);
    }

    #[test]
    fn compound_and_volume_conversions_work() {
        let mut service = service();
        let litre = service.submit("1 l -> dm^3");
        assert!((outval(&litre).unwrap() - 1.0).abs() < 1e-9);
        let speed = service.submit("100 km/h -> m/s");
        assert!((outval(&speed).unwrap() - 27.7777778).abs() < 1e-6);
        assert_eq!(speed.value.unwrap().unit_symbol(), Some("m/s"));
    }

    #[test]
    fn adding_compatible_units_auto_picks_a_unit() {
        let mut service = service();
        let outcome = service.submit("1 m + 50 cm");
        assert!((outval(&outcome).unwrap() - 1.5).abs() < 1e-9);
        assert_eq!(outcome.value.unwrap().unit_symbol(), Some("m"));
    }

    #[test]
    fn addition_with_units_picks_a_single_unit() {
        let mut service = service();
        let outcome = service.submit("20 kN + 300 N");
        let quantity = outcome.value.unwrap();
        // 20 kN + 300 N = 20.3 kN, shown with the short unit symbol.
        assert!((quantity.display_value() - 20.3).abs() < 1e-9);
        assert_eq!(quantity.unit_symbol(), Some("kN"));
    }

    #[test]
    fn multiplying_quantities_yields_a_derived_unit() {
        let mut service = service();
        let outcome = service.submit("1 m * 2 m");
        let quantity = outcome.value.unwrap();
        assert!((quantity.display_value() - 2.0).abs() < 1e-9);
        assert_eq!(quantity.unit_symbol(), Some("m^2"));
    }

    #[test]
    fn dividing_quantities_pins_the_conversion_target() {
        let mut service = service();
        let outcome = service.submit("2 kN / 4 m^2 -> kN/m^2");
        let quantity = outcome.value.unwrap();
        assert!((quantity.display_value() - 0.5).abs() < 1e-9);
        assert_eq!(quantity.unit_symbol(), Some("kN/m^2"));
    }

    #[test]
    fn unit_arithmetic_with_a_unit_variable_routes_to_rink() {
        let mut service = service();
        service.submit("f = 20 kN");
        let outcome = service.submit("f + 300 N");
        let quantity = outcome.value.unwrap();
        assert!((quantity.display_value() - 20.3).abs() < 1e-9);
    }

    #[test]
    fn an_incompatible_conversion_errors() {
        let mut service = service();
        let outcome = service.submit("5 N -> bar");
        assert!(outcome.error.is_some());
    }

    #[test]
    fn pure_math_is_unaffected_by_the_units_router() {
        let mut service = service();
        // `e` is a constant (rink knows it too) but must stay on meval.
        assert!((outval(&service.submit("e^0")).unwrap() - 1.0).abs() < 1e-9);
        // `sin` is a function, not a unit, and respects the angle mode.
        service.toggle_angle_mode();
        let outcome = service.submit("sin(90)");
        assert!((outval(&outcome).unwrap() - 1.0).abs() < 1e-9);
    }

    /// The status line and the persisted history show these verbatim, so they
    /// are behaviour, not implementation. `AppError` produces each of them.
    #[test]
    fn every_failure_mode_keeps_its_message() {
        let cases: &[(&[&str], &str)] = &[
            (&["ans"], "no previous answer"),
            (&["ans -> m"], "no previous answer"),
            (&["=x"], "no previous answer to save"),
            (&["1", "=1bad"], "invalid variable name: '1bad'"),
            (&["1", "=pi"], "'pi' is reserved and cannot be a variable"),
            (
                &["2+"],
                "cannot evaluate: Parse error: Missing argument at the end of \
                 expression.",
            ),
            (
                &["5 N -> bar"],
                "Conformance error: 5 newton (force) != 100 kilopascal \
                 (pressure)",
            ),
        ];
        for (lines, expected) in cases {
            let mut calc = service();
            let mut outcome = None;
            for line in *lines {
                outcome = Some(calc.submit(line));
            }
            let error = outcome.expect("a submitted line").error;
            assert_eq!(error.as_deref(), Some(*expected), "for {lines:?}");
        }
    }

    #[test]
    fn a_rink_message_is_not_prefixed_like_a_meval_one() {
        // rink names the offending unit itself; meval yields a fragment.
        let rink = service().submit("1 foounit -> m").error.expect("an error");
        assert!(rink.starts_with("No such unit"), "{rink}");

        let meval = service().submit("2+").error.expect("an error");
        assert!(meval.starts_with("cannot evaluate: "), "{meval}");
    }
}