rigless 0.2.0

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The target's side of a link beyond its frames: [`serve`], which runs one target of a board as an
//! engine's, a port whose far end is the engine, what an `Advance` hands the board and the draws it
//! keys, which gaps and which of the models' told the engine hasn't heard yet, and the run's report.

use std::any::Any;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fs;
use std::io::{Read, Write};
use std::net::TcpListener;

use super::{
    Advance, Frame, Gap, Instance, LinkError, Manifest, Reached, Report, Served, Set, Told,
    Triggers, VERSION, WireError, bytes_of, values_of,
};
use crate::chip::{Timeline, uart};
use crate::edge::Coupled;
use crate::emulator::{
    self, Driver, Finished, Host, NO_DEADLINE, Settled, Start, Stop, StopReason, WalkThreads,
};
use crate::image::{self, Image};
use crate::machine::Board;
use crate::mcu::{Mcu, Operate};
use crate::session::{Session, Unimplemented, Unmapped};
use crate::snapshot::{self, Reader, Snapshot, Store, Writer, store};
use crate::soc::Fault;
use crate::symbols::{self, Symbols};
use crate::time::VirtualNanos;
use crate::version::RUNTIME;

/// A serial port whose far end is the engine. What the engine delivered waits here for the controller to
/// take, and what the firmware sent waits for the next `Reached`. A word wider than a byte crosses as its
/// low byte, as it does to a host on a socket.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct EnginePort {
    toward_firmware: VecDeque<u8>,
    from_firmware: Vec<u8>,
}

impl EnginePort {
    /// Queues `bytes` for the controller to take, after anything still waiting.
    pub fn deliver(&mut self, bytes: &[u8]) {
        self.toward_firmware.extend(bytes);
    }

    /// What the firmware sent since the last call.
    pub fn take_sent(&mut self) -> Vec<u8> {
        std::mem::take(&mut self.from_firmware)
    }
}

store!(EnginePort);

impl uart::Peer for EnginePort {
    fn receive(&mut self, word: u16, _context: &mut Timeline<'_, '_>) {
        self.from_firmware.push(word.to_le_bytes()[0]);
    }

    fn transmit(&mut self, _now: VirtualNanos) -> Option<u16> {
        self.toward_firmware.pop_front().map(u16::from)
    }
}

/// The engine's port on the wire called `name`, or why there isn't one.
fn engine_port<'a>(board: &'a mut dyn Board, name: &str) -> Result<&'a mut EnginePort, LinkError> {
    let peer: &mut dyn Any = board.host_mut(name).ok_or_else(|| {
        LinkError::Misfit(format!("names a port {name} the board has no host on"))
    })?;
    peer.downcast_mut::<EnginePort>().ok_or_else(|| {
        LinkError::Misfit(format!(
            "names a port {name} whose far end isn't the engine"
        ))
    })
}

/// Hangs a port whose far end is the engine on every wire of the board a host may sit on, and answers
/// their names in the board's order. A board that won't take one, or won't hand it back, is refused here,
/// before `Manifest`, since the engine couldn't reach that port once the run started.
pub fn attach_engine_ports(board: &mut dyn Board) -> Result<Vec<&'static str>, LinkError> {
    let ports: Vec<&'static str> = board.hosts().into_iter().map(|wire| wire.name).collect();
    for &port in &ports {
        if !board.attach_host(port, Box::new(EnginePort::default())) {
            return Err(LinkError::Board(format!(
                "names a port {port} it won't take"
            )));
        }
        let handed_back = board.host_mut(port).is_some_and(|peer| {
            let peer: &dyn Any = peer;
            peer.is::<EnginePort>()
        });
        if !handed_back {
            return Err(LinkError::Board(format!(
                "takes a port on {port} and doesn't hand it back from host_mut"
            )));
        }
    }
    Ok(ports)
}

/// What the target holds from one `Advance` to the next: every input's value and every condition's as
/// the engine set them, in `Manifest`'s order, the seed the run's draws are keyed by, and how many
/// `Advance`s the board has been handed.
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Held {
    /// Every input's value.
    pub inputs: Vec<i64>,
    /// Every condition's value.
    pub conditions: Vec<i64>,
    /// The seed, `rigless run --link --seed`.
    pub seed: u64,
    /// How many `Advance`s the board has been handed, which is the next one's index.
    pub advances: u64,
}

impl Held {
    /// The board as built, under `seed`: every input at the value it rests at, every condition at zero,
    /// and no `Advance` yet.
    pub fn at_rest(edge: &dyn Coupled, seed: u64) -> Result<Self, WireError> {
        Ok(Self {
            inputs: values_of(edge.fields(), &edge.rest_wire())?,
            conditions: vec![0; edge.conditions().len()],
            seed,
            advances: 0,
        })
    }
}

/// Hands the board what `advance` carries: the conditions, whole, when any changed, then the inputs,
/// sensed whole, when any changed, then the step's draws, and each port's bytes to that port's queue.
/// `held` is what the target holds as it stands, `ports` names the ports in the order `Manifest` gave
/// them, and `now` is the instant the run stands at.
///
/// An instant the run can't reach from `now` is refused, since the run would never answer it: one behind
/// `now`, or one the virtual clock never gets to.
pub fn deliver(
    board: &mut dyn Board,
    held: &mut Held,
    ports: &[&str],
    advance: &Advance,
    now: VirtualNanos,
) -> Result<(), LinkError> {
    if advance.until >= NO_DEADLINE {
        return Err(LinkError::Misfit(format!(
            "asked to reach {} ns, and the virtual clock stops short of {} ns",
            advance.until.0, NO_DEADLINE.0
        )));
    }
    if advance.until < now {
        return Err(LinkError::Misfit(format!(
            "asked to reach {} ns when the run already stands at {} ns",
            advance.until.0, now.0
        )));
    }
    if advance.ports.len() != ports.len() {
        return Err(LinkError::Misfit(format!(
            "sent bytes for {} ports and the board has {}",
            advance.ports.len(),
            ports.len()
        )));
    }
    apply(&mut held.inputs, &advance.inputs, "input")?;
    apply(&mut held.conditions, &advance.conditions, "condition")?;
    match board.edge() {
        Some(edge) => {
            if !advance.conditions.is_empty() {
                edge.condition_wire(&bytes_of(edge.conditions(), &held.conditions)?)?;
            }
            if !advance.inputs.is_empty() {
                edge.sense_wire(&bytes_of(edge.fields(), &held.inputs)?)?;
            }
            edge.draw(held.seed, held.advances);
        }
        None if !advance.inputs.is_empty() || !advance.conditions.is_empty() => {
            return Err(LinkError::Board(
                "has no edge to sense the inputs or the conditions on".to_owned(),
            ));
        }
        None => {}
    }
    held.advances += 1;
    for (name, bytes) in ports.iter().zip(&advance.ports) {
        if !bytes.is_empty() {
            engine_port(board, name)?.deliver(bytes);
        }
    }
    Ok(())
}

/// Writes each of `sets` into `values`, refusing an index the board has no `what` at.
pub(super) fn apply(values: &mut [i64], sets: &[Set], what: &str) -> Result<(), LinkError> {
    let count = values.len();
    for set in sets {
        *values.get_mut(usize::from(set.index)).ok_or_else(|| {
            LinkError::Misfit(format!(
                "set {what} {} and the board has {count}",
                set.index
            ))
        })? = set.value;
    }
    Ok(())
}

/// What the firmware sent on each of `ports` since the last call, in their order.
pub fn sent(board: &mut dyn Board, ports: &[&str]) -> Result<Vec<Vec<u8>>, LinkError> {
    ports
        .iter()
        .map(|name| Ok(engine_port(board, name)?.take_sent()))
        .collect()
}

/// The gaps and what the models told, already passed on, so each crosses once, the first time the run
/// meets it.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(bound(deserialize = "'de: 'static"))]
pub struct Gaps {
    unmapped: BTreeSet<u64>,
    refused: BTreeSet<u64>,
    unimplemented: BTreeSet<u64>,
    unrouted: BTreeSet<(&'static str, u16)>,
    told: BTreeSet<(&'static str, &'static str, &'static str)>,
}

impl Gaps {
    /// Every gap `session` holds that hasn't been told yet.
    pub fn fresh<D: Board + ?Sized>(&mut self, session: &Session<D>) -> Vec<Gap> {
        self.fresh_in(
            &session.unmapped(),
            session.refused(),
            session.unimplemented(),
            session.unrouted(),
        )
    }

    fn fresh_in(
        &mut self,
        unmapped: &[Unmapped],
        refused: &BTreeMap<u64, Fault>,
        unimplemented: &BTreeMap<u64, Unimplemented>,
        unrouted: &BTreeSet<(&'static str, u16)>,
    ) -> Vec<Gap> {
        let mut gaps = Vec::new();
        for entry in unmapped {
            if self.unmapped.insert(entry.address) {
                gaps.push(Gap::Unmapped {
                    address: entry.address,
                    program_counter: entry.program_counter,
                });
            }
        }
        // A shut gate is the part saying no, as the silicon does, so it's the model and not a gap.
        let outstanding = refused.iter().filter(|(_, fault)| !fault.is_shut_gate());
        for (&address, fault) in outstanding {
            if self.refused.insert(address) {
                gaps.push(Gap::Refused {
                    address,
                    why: fault.to_string(),
                });
            }
        }
        for (&address, entry) in unimplemented {
            if self.unimplemented.insert(address) {
                gaps.push(Gap::Unimplemented {
                    instance: entry.instance.to_owned(),
                    register: entry.register.to_owned(),
                    address,
                    program_counter: entry.program_counter,
                });
            }
        }
        for &(instance, line) in unrouted {
            if self.unrouted.insert((instance, line)) {
                gaps.push(Gap::Unrouted {
                    instance: instance.to_owned(),
                    line,
                });
            }
        }
        gaps
    }

    /// Everything the models told `session` that hasn't crossed yet, keyed as `session` keys them.
    pub fn told<D: Board + ?Sized>(&mut self, session: &Session<D>) -> Vec<Told> {
        self.told_in(session.told())
    }

    fn told_in<'a>(&mut self, told: impl Iterator<Item = &'a crate::device::Told>) -> Vec<Told> {
        told.filter(|told| {
            self.told
                .insert((told.instance, told.register, told.reason))
        })
        .map(|told| Told {
            instance: told.instance.to_owned(),
            register: told.register.to_owned(),
            reason: told.reason.to_owned(),
            at: told.at,
        })
        .collect()
    }
}

/// What the run recorded, as `Report` carries it: every reset, and how many of each kind of gap the run
/// met. A shut gate is told nowhere, so it's counted nowhere.
#[must_use]
pub fn report<D: Board + ?Sized>(session: &Session<D>) -> Report {
    let count = |entries: usize| u64::try_from(entries).expect("a count fits");
    Report {
        resets: session.resets().iter().map(|reset| reset.at).collect(),
        unmapped: count(session.unmapped().len()),
        refused: count(
            session
                .refused()
                .values()
                .filter(|fault| !fault.is_shut_gate())
                .count(),
        ),
        unimplemented: count(session.unimplemented().len()),
        unrouted: count(session.unrouted().len()),
        told: count(session.told().count()),
    }
}

/// How [`serve`] starts an engine's target: the images it places, where the core boots, the debugger
/// it serves and the kernels it shows the threads of, the seed every draw is keyed by, and the
/// snapshot it carries on from, if any. `rigless run --link` fills one from its flags, starting from
/// [`Launch::new`].
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Launch<'a> {
    /// The images placed before the core's first instruction, the firmware first. A fault names an
    /// instruction by the firmware's symbols.
    pub images: &'a [Image],
    /// Where the core boots from, or `None` for where it boots on its own.
    pub boot: Option<u64>,
    /// The listener to serve the debugger on, if any, as [`Start::debugger`] takes it.
    pub debugger: Option<&'a TcpListener>,
    /// Hold the core before its first instruction until a debugger lets it go, as
    /// [`Start::wait_for_debugger`] says.
    pub wait_for_debugger: bool,
    /// What every random draw the board makes is keyed by. A target carrying on from a snapshot runs
    /// under the seed the snapshot was taken with instead.
    pub seed: u64,
    /// The snapshot to carry on from, of the same machine, target, images, boot address and runtime, or
    /// `None` to start from reset.
    pub restore: Option<&'a Snapshot>,
    /// The kernels whose threads the debugger shows, as [`Start::kernels`] takes them.
    pub kernels: &'a [Box<dyn WalkThreads>],
}

impl<'a> Launch<'a> {
    /// `images`, the firmware first, booted where the core boots on its own, with no debugger or
    /// kernels, under a seed of 0, from reset.
    #[must_use]
    pub fn new(images: &'a [Image]) -> Self {
        Self {
            images,
            boot: None,
            debugger: None,
            wait_for_debugger: false,
            seed: 0,
            restore: None,
            kernels: &[],
        }
    }
}

/// Why an engine's target couldn't be served to the end.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ServeError {
    /// The board has nothing a plant couples to.
    #[error("{machine} has no edge a plant couples to, so it can't be an engine's target")]
    NoEdge {
        /// The board, by the name it calls itself.
        machine: &'static str,
    },
    /// There's no image, and the first one is the firmware.
    #[error("an engine's target runs a firmware, and it was given no image")]
    NoFirmware,
    /// The engine asked for a snapshot before the run had stopped anywhere.
    #[error("the engine asked for a snapshot before the run had a stop to take it at")]
    SnapshotBeforeStop,
    /// The link broke, or carried something the board can't take.
    #[error(transparent)]
    Link(#[from] LinkError),
    /// The emulator, or the session over it, failed.
    #[error(transparent)]
    Emulator(#[from] emulator::Error),
    /// The snapshot to carry on from couldn't be restored.
    #[error(transparent)]
    Snapshot(#[from] snapshot::Error),
}

impl From<WireError> for ServeError {
    fn from(error: WireError) -> Self {
        Self::Link(error.into())
    }
}

/// Runs the target at `target` on `board` as the target of the engine on the far side of `served`,
/// until the engine shuts it down. That's `rigless run --link`, for any board with an edge.
///
/// The board's edge, its ports, the part's instances and the board's chips are the `Manifest`. Every
/// `Advance` hands the board what it carries, arms its faults and runs to its instant, and the target
/// answers `Reached`. A `Snapshot` is written where the run stands, and one that can't be taken is
/// `Refused` with why while the run goes on. `Shutdown` is answered with the run's `Report`.
///
/// # Errors
///
/// A board with no edge or one that declares what it doesn't carry, no firmware among the images, a
/// link that breaks or carries what the board can't take, a snapshot that can't be restored, and
/// whatever the emulator or the session met.
pub fn serve<R, W>(
    mut board: Box<dyn Board>,
    target: usize,
    launch: &Launch<'_>,
    served: Served<R, W>,
) -> Result<(), ServeError>
where
    R: Read + Send + 'static,
    W: Write + Send + 'static,
{
    let name = board.name();
    let firmware = launch.images.first().ok_or(ServeError::NoFirmware)?;
    let Some(edge) = board.edge() else {
        return Err(ServeError::NoEdge { machine: name });
    };
    edge.check().map_err(emulator::Error::from)?;
    let (inputs, outputs, conditions, chips) = (
        edge.fields(),
        edge.output_fields(),
        edge.conditions(),
        edge.chips(),
    );
    let held = Held::at_rest(edge, launch.seed)?;
    let ports = attach_engine_ports(&mut *board)?;
    let code_address: fn(u64) -> u64 = board
        .targets()
        .get(target)
        .map_or(std::convert::identity, |chosen| chosen.core.code_address);
    let count = board.target_names().len();
    let mcu = board.mcu(target).ok_or(emulator::Error::NoTarget {
        machine: name,
        target,
        count,
    })?;
    let manifest = Manifest {
        version: VERSION,
        machine: name.to_owned(),
        runtime: RUNTIME.to_owned(),
        snapshot: launch.restore.map(Snapshot::hash),
        inputs: inputs.to_vec(),
        rest: held.inputs.clone(),
        outputs: outputs.to_vec(),
        ports: ports.iter().map(ToString::to_string).collect(),
        conditions: conditions.to_vec(),
        instances: instances(mcu),
        chips: chips.iter().map(ToString::to_string).collect(),
        lines: mcu.cpu().interrupt_lines,
    };
    let mut driver = Serving {
        served,
        held,
        ports,
        gaps: Gaps::default(),
        resets_told: 0,
        triggers: Triggers::default(),
        symbols: Symbols::read(firmware.bytes(), code_address),
        firmware: image::digest(launch.images, launch.boot),
        failed: None,
    };
    let mut session = Session::new(board, target, VirtualNanos(0))?;
    // Loaded and checked before `Manifest` says the target started from it.
    let resume = match launch.restore {
        Some(restored) => {
            let digest = driver.firmware;
            Some(restored.restore(&mut session, &digest, &mut driver)?)
        }
        None => None,
    };
    // Where the run stands before its first instruction: at reset, or at the stop the snapshot was
    // taken at.
    let standing = launch.restore.map_or(
        Stop {
            at: VirtualNanos(0),
            instruction_count: 0,
            reason: StopReason::Deadline,
        },
        Snapshot::stop,
    );
    driver.served.open(&manifest)?;
    // The engine says where to reach first, before anything runs.
    let first = match driver.served.receive()? {
        Frame::Advance(first) => first,
        Frame::Shutdown => {
            driver.served.report(report(&session))?;
            return Ok(());
        }
        // `receive` answers nothing else.
        _ => return Err(ServeError::SnapshotBeforeStop),
    };
    deliver(
        session.board_mut(),
        &mut driver.held,
        &driver.ports,
        &first,
        standing.at,
    )?;
    // A run from reset pauses where it stands before its first instruction, which the models never
    // hear of, so what the first step arms starts and fires there with the emulator to hand. A
    // restored one does it at the stop it resumes at, where the run that took the snapshot did.
    if launch.restore.is_none() && !first.armed.is_empty() {
        session.pause_at(Some(standing.at));
    }
    driver
        .triggers
        .arm(first.armed, &mut session, standing, driver.symbols.as_ref())?;
    session.run_until(first.until);
    let mut start = Start::new(launch.images);
    start.boot = launch.boot;
    start.debugger = launch.debugger;
    start.wait_for_debugger = launch.wait_for_debugger;
    start.resume = resume.as_ref();
    start.kernels = launch.kernels;
    let Finished {
        mut session,
        mut driver,
        ..
    } = emulator::run(session, &start, driver)?;
    if let Some(error) = driver.failed.take() {
        return Err(error);
    }
    if let Some(error) = session.take_error() {
        return Err(error.into());
    }
    driver.served.report(report(&session))?;
    Ok(())
}

/// Every instance `mcu` carries with its registers, by their names, in the bus's order.
fn instances(mcu: &mut dyn Mcu) -> Vec<Instance> {
    mcu.bus()
        .peripherals()
        .map(|peripheral| Instance {
            name: peripheral.name.to_owned(),
            registers: peripheral
                .registers
                .iter()
                .map(|register| register.name.to_owned())
                .collect(),
        })
        .collect()
}

/// `error` and every error beneath it, as one line, which is how an engine hears why a snapshot was
/// refused.
fn said(error: &dyn std::error::Error) -> String {
    let mut said = error.to_string();
    let mut beneath = error.source();
    while let Some(cause) = beneath {
        said.push_str(": ");
        said.push_str(&cause.to_string());
        beneath = cause.source();
    }
    said
}

/// The driver of an engine's target: the link, what the engine set, and what the run has told it.
struct Serving<R: Read, W: Write> {
    served: Served<R, W>,
    held: Held,
    ports: Vec<&'static str>,
    gaps: Gaps,
    resets_told: usize,
    triggers: Triggers,
    /// The firmware's symbols, which a fault names an instruction by, or why they couldn't be read.
    symbols: Result<Symbols, symbols::Error>,
    /// What a snapshot names the run's firmware by: every image, where each goes, and where the core
    /// boots from.
    firmware: [u8; 32],
    failed: Option<ServeError>,
}

impl<R: Read, W: Write> Serving<R, W> {
    /// Answers the engine at `stop` with what the run reached, then takes its next word: an `Advance`
    /// is the next instant to reach, a `Snapshot` is written and answered while the run stands here,
    /// and anything else ends the run.
    fn answer(
        &mut self,
        session: &mut Session<dyn Board>,
        stop: Stop,
        host: &mut dyn Host,
    ) -> Result<Option<VirtualNanos>, ServeError> {
        let edge = session
            .board_mut()
            .edge()
            .ok_or_else(|| LinkError::Board("lost its edge in the middle of a run".to_owned()))?;
        let outputs = values_of(edge.output_fields(), &edge.drive_wire())?;
        let ports = sent(session.board_mut(), &self.ports)?;
        let resets = session.resets()[self.resets_told..]
            .iter()
            .map(|reset| reset.at)
            .collect::<Vec<_>>();
        self.resets_told = session.resets().len();
        let gaps = self.gaps.fresh(session);
        let told = self.gaps.told(session);
        self.served.reached(Reached {
            stop,
            outputs,
            ports,
            resets,
            gaps,
            told,
            fired: self.triggers.take_fired(),
        })?;
        loop {
            match self.served.receive()? {
                Frame::Advance(advance) => {
                    deliver(
                        session.board_mut(),
                        &mut self.held,
                        &self.ports,
                        &advance,
                        stop.at,
                    )?;
                    self.triggers
                        .arm(advance.armed, session, stop, self.symbols.as_ref())?;
                    self.triggers
                        .settled(session, host, &mut self.held, Settled::Stop(stop))?;
                    return Ok(Some(advance.until));
                }
                Frame::Snapshot(asked) => {
                    // A snapshot that can't be taken or written leaves the run as it stood, so the
                    // engine hears why and the run goes on.
                    let written = snapshot::take(session, host, stop, &self.firmware, self)
                        .map_err(|error| said(&error))
                        .and_then(|taken| {
                            fs::write(&asked.path, &taken.file).map_err(|error| {
                                format!("writing the snapshot to {}: {}", asked.path, said(&error))
                            })?;
                            Ok(taken.hash)
                        });
                    match written {
                        Ok(hash) => self.served.snapshotted(hash)?,
                        Err(why) => self.served.refused(why)?,
                    }
                }
                _ => return Ok(None),
            }
        }
    }
}

/// What the link keeps across a snapshot: every value the engine set and the seed, how much of what
/// the run met the engine has already heard, and the faults armed with how far each has counted.
impl<R: Read, W: Write> Store for Serving<R, W> {
    fn store(&self, to: &mut Writer) -> Result<(), snapshot::Error> {
        let Self {
            held,
            gaps,
            resets_told,
            triggers,
            served: _,
            ports: _,
            symbols: _,
            firmware: _,
            failed: _,
        } = self;
        to.put(held)?;
        to.put(gaps)?;
        to.put(resets_told)?;
        to.put(triggers)
    }

    fn load(&mut self, from: &mut Reader) -> Result<(), snapshot::Error> {
        let Self {
            held,
            gaps,
            resets_told,
            triggers,
            served: _,
            ports: _,
            symbols: _,
            firmware: _,
            failed: _,
        } = self;
        *held = from.take()?;
        *gaps = from.take()?;
        *resets_told = from.take()?;
        *triggers = from.take()?;
        Ok(())
    }
}

impl<R: Read + Send, W: Write + Send> Driver<dyn Board> for Serving<R, W> {
    /// Counts toward every armed fault, and fires those due. A failure ends the run at the step's end,
    /// since nothing here can answer the engine.
    fn on_settled(
        &mut self,
        session: &mut Session<dyn Board>,
        host: &mut dyn Host,
        settled: Settled,
    ) {
        if self.failed.is_some() {
            return;
        }
        if let Err(error) = self
            .triggers
            .settled(session, host, &mut self.held, settled)
        {
            self.failed = Some(error.into());
        }
    }

    fn on_stop(
        &mut self,
        session: &mut Session<dyn Board>,
        stop: Stop,
        host: &mut dyn Host,
    ) -> Option<VirtualNanos> {
        if self.failed.is_some() {
            return None;
        }
        self.answer(session, stop, host).unwrap_or_else(|error| {
            self.failed = Some(error);
            None
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chip::uart::Peer;
    use crate::machine::{HostWire, Target};
    use crate::mcu::Mcu;
    use crate::soc::Gate;

    /// A board with one wire a host sits on, which gives the host back only if it `hands_back`.
    #[derive(Debug)]
    struct Wired {
        peer: Option<Box<dyn Peer>>,
        hands_back: bool,
    }

    impl Wired {
        fn handing_back(hands_back: bool) -> Self {
            Self {
                peer: None,
                hands_back,
            }
        }
    }

    impl Store for Wired {}

    impl Board for Wired {
        fn name(&self) -> &'static str {
            "wired"
        }

        fn targets(&mut self) -> Vec<Target<'_>> {
            Vec::new()
        }

        fn target_names(&self) -> Vec<&'static str> {
            Vec::new()
        }

        fn mcu(&mut self, _target: usize) -> Option<&mut dyn Mcu> {
            None
        }

        fn hosts(&self) -> Vec<HostWire> {
            vec![HostWire {
                name: "wire1",
                port: 0,
            }]
        }

        fn attach_host(&mut self, name: &str, peer: Box<dyn Peer>) -> bool {
            self.peer = Some(peer);
            name == "wire1"
        }

        fn host_mut(&mut self, name: &str) -> Option<&mut dyn Peer> {
            match &mut self.peer {
                Some(peer) if self.hands_back && name == "wire1" => Some(peer.as_mut()),
                _ => None,
            }
        }
    }

    fn quiet(until: u64) -> Advance {
        Advance {
            until: VirtualNanos(until),
            inputs: Vec::new(),
            ports: vec![Vec::new()],
            conditions: Vec::new(),
            armed: Vec::new(),
        }
    }

    #[test]
    fn a_board_that_does_not_hand_its_port_back_is_refused_before_the_manifest() {
        let mut board = Wired::handing_back(true);
        assert_eq!(attach_engine_ports(&mut board).unwrap(), ["wire1"]);
        let mut board = Wired::handing_back(false);
        assert!(matches!(
            attach_engine_ports(&mut board),
            Err(LinkError::Board(why)) if why.contains("wire1")
        ));
    }

    #[test]
    fn an_instant_behind_the_run_or_past_the_clock_is_refused_and_the_one_it_stands_at_is_not() {
        let mut board = Wired::handing_back(true);
        let ports = attach_engine_ports(&mut board).unwrap();
        let now = VirtualNanos(10);
        let mut deliver_at =
            |until| deliver(&mut board, &mut Held::default(), &ports, &quiet(until), now);
        assert!(matches!(deliver_at(9), Err(LinkError::Misfit(_))));
        assert!(matches!(
            deliver_at(NO_DEADLINE.0),
            Err(LinkError::Misfit(_))
        ));
        assert!(matches!(deliver_at(u64::MAX), Err(LinkError::Misfit(_))));
        assert!(
            deliver_at(10).is_ok(),
            "a step of no length is still a step"
        );
        assert!(deliver_at(NO_DEADLINE.0 - 1).is_ok());
    }

    #[test]
    fn an_engine_port_hands_the_controller_its_bytes_in_order_and_keeps_what_the_firmware_sent() {
        let mut port = EnginePort::default();
        port.deliver(b"ab");
        port.deliver(b"c");
        let taken: Vec<Option<u16>> = (0..4).map(|_| port.transmit(VirtualNanos(0))).collect();
        assert_eq!(
            taken,
            [
                Some(u16::from(b'a')),
                Some(u16::from(b'b')),
                Some(u16::from(b'c')),
                None
            ]
        );
        port.from_firmware.extend([1, 2]);
        assert_eq!(port.take_sent(), [1, 2]);
        assert!(port.take_sent().is_empty(), "each byte is told once");
    }

    #[test]
    fn each_gap_is_told_once_the_first_time_it_is_met_and_a_shut_gate_is_none() {
        let mut gaps = Gaps::default();
        let unmapped = [Unmapped {
            address: 0x1000,
            program_counter: 0x20,
        }];
        let refused = BTreeMap::from([
            (0x2000, Fault::Unmapped { address: 0x2000 }),
            (
                0x2400,
                Fault::Gated {
                    instance: "TIMER",
                    register: "CONTROL",
                    by: Gate {
                        instance: "CLOCKS",
                        register: "ENABLE",
                        field: "TIMEREN",
                    },
                },
            ),
        ]);
        let unimplemented = BTreeMap::from([(
            0x3000,
            Unimplemented {
                instance: "TIMER",
                register: "CONTROL",
                program_counter: 0x30,
                reads: 1,
                writes: 0,
                written: None,
            },
        )]);
        let unrouted = BTreeSet::from([("TIMER", 7)]);
        let first = gaps.fresh_in(&unmapped, &refused, &unimplemented, &unrouted);
        assert_eq!(
            first,
            [
                Gap::Unmapped {
                    address: 0x1000,
                    program_counter: 0x20
                },
                Gap::Refused {
                    address: 0x2000,
                    why: "no register at 0x2000".to_owned()
                },
                Gap::Unimplemented {
                    instance: "TIMER".to_owned(),
                    register: "CONTROL".to_owned(),
                    address: 0x3000,
                    program_counter: 0x30
                },
                Gap::Unrouted {
                    instance: "TIMER".to_owned(),
                    line: 7
                },
            ]
        );
        assert!(
            gaps.fresh_in(&unmapped, &refused, &unimplemented, &unrouted)
                .is_empty(),
            "nothing new the second time"
        );
    }

    #[test]
    fn each_thing_a_model_told_crosses_once() {
        let mut gaps = Gaps::default();
        let told = |register, at| crate::device::Told {
            instance: "BUS",
            register,
            reason: "the model says no",
            at: VirtualNanos(at),
        };
        let first = [told("CONTROL", 5)];
        assert_eq!(
            gaps.told_in(first.iter()),
            [Told {
                instance: "BUS".to_owned(),
                register: "CONTROL".to_owned(),
                reason: "the model says no".to_owned(),
                at: VirtualNanos(5),
            }]
        );
        let later = [told("CONTROL", 5), told("STATUS", 9)];
        assert_eq!(
            gaps.told_in(later.iter())
                .iter()
                .map(|told| told.register.as_str())
                .collect::<Vec<_>>(),
            ["STATUS"],
            "only what hasn't crossed yet"
        );
    }
}