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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! What a peripheral model implements, and the register file the runtime keeps for it.
//!
//! A model is written against one generated register layout and does only what the hardware
//! does beyond storing bits. Everything a table can express is applied by the [`RegisterFile`]:
//! reset values, read-only bits, write-one-to-clear and write-once before the model sees a write,
//! and read-to-clear only when the model leaves a read to the file.
//!
//! ```
//! use rigless::device::{Device, RegisterFile};
//! # use rigless::soc::{Access, Layout, ReadAction, RegisterSpec, Width, WriteModify};
//! # static REGISTERS: [RegisterSpec; 1] = [RegisterSpec { name: "DR", offset: 0, width: Width::W32, reset: 0, access: Access::ReadWrite, read: ReadAction::None, write: WriteModify::None, fields: &[] }];
//! # #[derive(Debug, Clone, Copy)] enum Register { Dr }
//! # impl Layout for Register { const REGISTERS: &'static [RegisterSpec] = &REGISTERS; fn from_index(index: usize) -> Option<Self> { (index == 0).then_some(Self::Dr) } fn index(self) -> usize { 0 } }
//!
//! # use rigless::device::DeviceContext;
//! /// A UART that collects every byte the firmware sends.
//! #[derive(Default)]
//! struct Uart { sent: Vec<u8> }
//!
//! impl Device for Uart {
//!     type Register = Register;
//!     fn write(&mut self, register: Register, value: u64, _registers: &mut RegisterFile, _context: &mut DeviceContext<'_>) {
//!         if let Register::Dr = register { self.sent.push(value as u8); }
//!     }
//! }
//! ```
//!
//! A model that keeps time schedules an event through its [`DeviceContext`] and is woken by
//! [`Device::on_event`] at that instant, whether or not the firmware touches it meanwhile.
//!
//! A model that decides the part itself should restart, a watchdog reaching its own end of count,
//! asks with [`DeviceContext::request_reset`] rather than resetting anything itself: the part names no
//! model, so this is where a peripheral hands the decision to the one place that may act on it.
//!
//! A model that needs another instance does not reach it. It drives a request line the other reads
//! with [`DeviceContext::request`] and takes one at [`Device::on_request`]. It drives a clock the
//! other runs on with [`DeviceContext::clock`] and takes a change of its own at
//! [`Device::on_clock`]. It asks the runtime for an access with [`DeviceContext::read_from`] and is
//! answered at [`Device::on_access`], or told the bus refused at [`Device::on_refused`]. Those
//! three, and the gate that decides whether an instance answers at all, are written down under
//! *Joining one instance to another* in [`crate::soc`].

use std::collections::VecDeque;

use crate::emulator::{AccessKind, InterruptLine};
use crate::snapshot::store;
use crate::soc::{Access, FieldSpec, Layout, Peripheral, RegisterSpec, Width, WriteModify};
use crate::time::{EventId, EventQueue, VirtualNanos};

/// A peripheral model: the side effects of reads, writes, and its own events on one register layout.
///
/// Every method defaults to doing nothing, so a model overrides only what it needs. Between calls a
/// model does not exist: it may not keep a thread or read a wall clock. Nor may it reach another
/// instance directly. It asks, through [`DeviceContext::read_from`] and
/// [`DeviceContext::write_to`], and is answered at [`Device::on_access`].
pub trait Device {
    /// The register layout the model is written for.
    type Register: Layout;

    /// The layout the instance this model is answering for carries, where the part's own table for it
    /// is shorter than the one the model is written against.
    ///
    /// A model answers for every instance of its layout, and a vendor sometimes gives one instance
    /// a register another has not. Where that shorter table is a prefix of this one, with the same
    /// registers at the same rows until it stops, the model reaches every row that exists, and the
    /// rows that don't exist are never asked for. Returning that table is how a model says so, and
    /// it is what the wiring check holds the slot to. The default is the model's own, which is
    /// every other model.
    fn layout(&self) -> &'static [RegisterSpec] {
        <Self::Register as Layout>::REGISTERS
    }

    /// Answers a read, or returns `None` to serve the register file's value.
    ///
    /// The file's own read side effects, such as read-to-clear, apply only when the model
    /// returns `None`.
    fn read(
        &mut self,
        _register: Self::Register,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) -> Option<u64> {
        None
    }

    /// What a read of `register` would answer at `now`, with nothing changed, or `None` for what the
    /// register file holds. That's a debugger's read, which the run never hears of.
    ///
    /// `None` takes no read action, so read-to-clear doesn't apply, and a register the bus can't read
    /// answers 0. Answer it yourself only where your read answers something the file doesn't hold,
    /// like the byte at the front of a FIFO or a counter that runs on time. It takes `&self` and the
    /// file shared, so a peek can't change the part. The runtime asks only once every event due by
    /// `now` has fired and the part has settled, as it has between two instructions, so a peek
    /// needn't catch up the way a read that settles first does.
    fn peek(
        &self,
        _register: Self::Register,
        _registers: &RegisterFile,
        _now: VirtualNanos,
    ) -> Option<u64> {
        None
    }

    /// Reacts to a write.
    ///
    /// `value` is what arrived at the full register width. The file already holds what landed after
    /// the access and write-modify rules.
    fn write(
        &mut self,
        _register: Self::Register,
        _value: u64,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) {
    }

    /// Reacts to an event the model scheduled, at its instant.
    ///
    /// `event` is the id [`DeviceContext::schedule`] returned, an [`EventId`] from the [`crate::time`] module
    /// beside the clock it names an instant on. A model that scheduled again since ignores an id it no
    /// longer expects. There is no cancel.
    fn on_event(
        &mut self,
        _event: EventId,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) {
    }

    /// Reacts to a request another instance drives, for a model the description made a sink.
    ///
    /// The change names the instance driving it and that instance's own numbering of the output, so a
    /// controller reads its own wiring to learn which of its channels it is. A sink sees every request on the part
    /// and ignores the ones its wiring does not name.
    fn on_request(
        &mut self,
        _request: RequestChange,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) {
    }

    /// Takes a change of an interrupt another instance drives, for the model the description named
    /// with [`Builder::routes_interrupts`](crate::soc::Builder::routes_interrupts): an interrupt
    /// controller on the part's side of the core, which drives the core's lines itself with
    /// [`DeviceContext::drive_line`].
    ///
    /// The change names the instance and its number in the part's numbering, so the controller
    /// reads its own registers to learn which line, if any, it reaches.
    fn on_interrupt(
        &mut self,
        _change: InterruptChange,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) {
    }

    /// Takes a change of rate of the clock this instance runs on, for a model the description wired to one.
    ///
    /// `hz` is the new rate from this instant on, and zero is a clock that has stopped. A model that keeps
    /// time re-bases here: what it had counted stands, and from `context.now()` it counts at `hz`. Events
    /// it has scheduled were placed at the old rate, so it schedules again where they move.
    fn on_clock(
        &mut self,
        _hz: u64,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) {
    }

    /// Takes the answer to an access this model asked the runtime to make.
    ///
    /// `token` is the one given to [`DeviceContext::read_from`] or [`DeviceContext::write_to`], and `value`
    /// is what a read found or zero for a write.
    fn on_access(
        &mut self,
        _token: u64,
        _value: u64,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) {
    }

    /// Takes the news that an access this model asked for was refused, with the model's own `token`.
    ///
    /// The bus answers a refusal to nobody, so a model left waiting on one waits forever. What a
    /// refusal means is the model's to decide. A controller ends its transfer on it, as it would on
    /// a bus error. The run reports it as well, the way it reports a firmware's refused access.
    fn on_refused(
        &mut self,
        _token: u64,
        _registers: &mut RegisterFile,
        _context: &mut DeviceContext<'_>,
    ) {
    }

    /// Called at every stop of the target's emulator, which is at every event and at every instant the
    /// run was asked to reach, for a model with something outside it that isn't one of its accesses or
    /// events: a host on a wire, which has whatever it has when the runtime looks, or a chip the model
    /// holds with words of its own to send, which [`chip::uart::Peer::transmit`](crate::chip::uart::Peer::transmit)
    /// hands over at the first stop after they're due. A model with nothing outside leaves it.
    fn poll(&mut self, _registers: &mut RegisterFile, _context: &mut DeviceContext<'_>) {}

    /// The part restarted: put back what a reset clears in the model, as its registers already are.
    /// The reset dropped every event, so a model forgets the one it was waiting for. It can come twice
    /// for one restart, when a second cause joins the first, so it puts state back and counts nothing.
    /// Nothing by default, for a model that keeps nothing a reset clears.
    fn reset(&mut self) {}
}

/// What a model may do beyond its registers during one call: read the clock, schedule an event, raise or
/// lower one of its instance's interrupts, drive a request or a clock, ask for an access, ask for a
/// reset, and tell the session about its own instance.
///
/// The SoC builds one for the instance it is calling, so a model sees its own time and interrupts and nothing else.
#[derive(Debug)]
pub struct DeviceContext<'a> {
    now: VirtualNanos,
    owner: usize,
    instance: &'static str,
    interrupts: &'static [u16],
    effects: &'a mut Effects,
}

/// What the models put down during a call and the runtime takes away after it: the events they scheduled,
/// the interrupt and request levels they set, the clock rates they drove, the accesses they asked for and
/// the answers to those, the reset they asked for, and what they told the session about their own
/// instances.
///
/// They are one thing because they are one thing to the runtime: everything a model does beyond its own
/// registers happens here, after the call that caused it has returned.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(bound(deserialize = "'de: 'static"))]
pub(crate) struct Effects {
    pub(crate) events: EventQueue,
    pub(crate) interrupts: VecDeque<(VirtualNanos, InterruptChange)>,
    /// What an interrupt controller on the part drove onto the core's lines. Every call that drives
    /// one is drained before the run stops, so a snapshot finds none.
    #[serde(skip)]
    pub(crate) lines: Vec<LineChange>,
    pub(crate) requests: VecDeque<(VirtualNanos, RequestChange)>,
    pub(crate) clocks: VecDeque<(VirtualNanos, ClockChange)>,
    pub(crate) accesses: VecDeque<PendingAccess>,
    pub(crate) answers: VecDeque<Answer>,
    /// The first model this settle asked for a system reset, if one did. First rather than last: once
    /// one instance has asked, the part is about to be rebuilt, so a second ask in the same settle
    /// changes nothing and is not worth ordering.
    pub(crate) reset: Option<ResetCause>,
    pub(crate) told: Vec<Told>,
}

/// Why the part is restarting, in the runtime's own vocabulary: never a part's name for the cause.
///
/// The core's own request is not [`ResetCause::Model`]: it reaches [`crate::mcu::Mcu::reset`] through
/// the emulator's own stop, since the core asks the emulator directly and no model is involved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum ResetCause {
    /// The core's own reset request, outside any model.
    Core,
    /// The named instance decided, from inside its own [`Device`] methods, that the part should
    /// restart rather than continue running: a watchdog reaching its own end of count is this.
    Model(&'static str),
    /// The part's reset pin, driven low from outside it: a fault a run fired with
    /// [`crate::session::Session::reset_by_pin`].
    Pin,
}

/// What an access a model asked for came back with.
///
/// It waits its turn rather than reaching the model inside the access that produced it, because the access
/// may itself have changed a request level and a model asked for its answer first would read the level as
/// it stood before its own access. It is the order the hardware has: a peripheral releases its request
/// when whatever it asked reaches it, and that reader sees the release.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) struct Answer {
    /// The instant the access that produced it was asked for.
    pub(crate) at: VirtualNanos,
    /// The slot that asked.
    pub(crate) owner: usize,
    /// The model's own tag from the access.
    pub(crate) token: u64,
    /// What a read found, zero for a write, or nothing where the bus refused the access.
    pub(crate) found: Option<u64>,
}

impl<'a> DeviceContext<'a> {
    pub(crate) fn new(
        now: VirtualNanos,
        owner: usize,
        peripheral: Peripheral,
        effects: &'a mut Effects,
    ) -> Self {
        Self {
            now,
            owner,
            instance: peripheral.name,
            interrupts: peripheral.interrupts,
            effects,
        }
    }

    /// The instant of this call on the virtual clock.
    #[must_use]
    pub fn now(&self) -> VirtualNanos {
        self.now
    }

    /// Schedules an event for this instance at `at`, an absolute instant. One already passed fires
    /// at the next stop.
    ///
    /// An instant this instance already has an event at gives that event's id back rather than a second
    /// event, so asking for the same instant on every access costs nothing and fires once.
    pub fn schedule(&mut self, at: VirtualNanos) -> EventId {
        self.effects.events.schedule(at.max(self.now), self.owner)
    }

    /// Sets the level of the instance's `position`-th interrupt, as its table lists them.
    ///
    /// An interrupt is a level, held until changed, the way a request is. The model owns the edge: a level
    /// driven again is reported again, so a model that should report only changes keeps the last one it
    /// drove and writes `context.interrupt(GLOBAL, wanted)` when it differs.
    /// [`DeviceContext::raise`] and [`DeviceContext::lower`] are this with the level named.
    ///
    /// A model names the position once, `const UPDATE: usize = 0`, since a layout shared by several
    /// instances cannot know an instance's number.
    ///
    /// # Panics
    ///
    /// Panics on a position the instance's table does not list, which is a bug in the model.
    pub fn interrupt(&mut self, position: usize, level: Level) {
        let Some(&interrupt) = self.interrupts.get(position) else {
            panic!(
                "{} lists {} interrupts, and the model asked for position {position}",
                self.instance,
                self.interrupts.len()
            );
        };
        self.effects.interrupts.push_back((
            self.now,
            InterruptChange {
                instance: self.instance,
                interrupt,
                level,
            },
        ));
    }

    /// Drives the core's interrupt `line` to `level`, for an interrupt controller on the part's
    /// side of the core, the one the description named with
    /// [`Builder::routes_interrupts`](crate::soc::Builder::routes_interrupts). The core takes it
    /// before its next instruction, as it takes any other line.
    pub fn drive_line(&mut self, line: InterruptLine, level: Level) {
        self.effects.lines.push(LineChange { line, level });
    }

    /// Raises the instance's `position`-th interrupt. See [`DeviceContext::interrupt`].
    pub fn raise(&mut self, position: usize) {
        self.interrupt(position, Level::High);
    }

    /// Lowers the instance's `position`-th interrupt. See [`DeviceContext::interrupt`].
    pub fn lower(&mut self, position: usize) {
        self.interrupt(position, Level::Low);
    }

    /// Drives the instance's `request`-th request output, in the instance's own numbering.
    ///
    /// A request is a level, held until changed, the way an interrupt is. The model owns the edge,
    /// so a level driven again is reported again, and a model that reports only changes keeps the
    /// last one it drove. Which instances read it is the description's to say, and what it means is
    /// the reader's: a controller wired to this instance knows which of its channels the number
    /// belongs to.
    pub fn request(&mut self, request: usize, level: Level) {
        self.effects.requests.push_back((
            self.now,
            RequestChange {
                instance: self.instance,
                request,
                level,
            },
        ));
    }

    /// Drives the instance's `output`-th clock output at `hz`, in the instance's own numbering.
    ///
    /// A clock is a rate rather than a level: what one instance's tree feeds another, which the reader
    /// counts on. The description says which instance runs on which output, and a reader is told only of
    /// its own, at [`Device::on_clock`]. A rate driven again is delivered again, so a model that drives
    /// only changes keeps the last rate it drove, as it does for a request.
    pub fn clock(&mut self, output: usize, hz: u64) {
        self.effects.clocks.push_back((
            self.now,
            ClockChange {
                instance: self.instance,
                output,
                hz,
            },
        ));
    }

    /// Asks the runtime to restart the part from its reset vector, at this instant, as this instance.
    ///
    /// It takes effect once this call returns and before the emulated core executes another
    /// instruction, the same as the core's own reset request. There is no re-entrancy and nothing to
    /// undo: this returns like any other effect, and the part underneath a model that keeps running
    /// past this call is the one about to be replaced. The cause the runtime records is always
    /// [`ResetCause::Model`] naming this instance, never [`ResetCause::Core`], so a model has no way
    /// to pass its own request off as the core's.
    pub fn request_reset(&mut self) {
        self.effects
            .reset
            .get_or_insert(ResetCause::Model(self.instance));
    }

    /// Asks the runtime to read `width` at `address` and hand the value back to [`Device::on_access`],
    /// tagged `token`.
    ///
    /// The access happens after this call returns, through the same path a firmware's would take,
    /// so a peripheral it lands on sees it as an ordinary access and a gate refuses it as one. An
    /// access that lies wholly inside one of the part's memory regions reaches the emulator's memory.
    /// One that runs past a region's end goes to the bus. `token` is the model's own, means nothing
    /// to the runtime, and comes back untouched. A refusal comes back to [`Device::on_refused`]
    /// carrying the same one.
    pub fn read_from(&mut self, address: u64, width: Width, token: u64) {
        self.effects.accesses.push_back(PendingAccess {
            at: self.now,
            owner: self.owner,
            token,
            kind: AccessKind::Read,
            address,
            width,
            value: 0,
        });
    }

    /// Asks the runtime to write `value` of `width` at `address`. See [`DeviceContext::read_from`].
    pub fn write_to(&mut self, address: u64, width: Width, value: u64, token: u64) {
        self.effects.accesses.push_back(PendingAccess {
            at: self.now,
            owner: self.owner,
            token,
            kind: AccessKind::Write,
            address,
            width,
            value,
        });
    }

    /// Tells the session `reason` about `register` once, on the transition into a condition an access
    /// already landed under with nothing to refuse, and not again on every access still held under it.
    pub fn tell(&mut self, register: &'static str, reason: &'static str) {
        self.effects.told.push(Told {
            instance: self.instance,
            register,
            reason,
            at: self.now,
        });
    }
}

/// What a model told the session about its own instance, without a bus access to refuse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Told {
    /// The instance, as the vendor names it.
    pub instance: &'static str,
    /// The register the condition concerns.
    pub register: &'static str,
    /// Why the model told it, cited to the manual's section.
    pub reason: &'static str,
    /// The instant of the access that first found the condition true.
    pub at: VirtualNanos,
}

/// A level a model set on one of its instance's request outputs, in the instance's own numbering.
///
/// A request is an interrupt's shape on another wire: a level one peripheral drives and another
/// reads, such as the serial interface telling a DMA controller it has a byte. The description says
/// which instances receive them, and the receiver decides what an instance's request means to it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RequestChange {
    /// The instance driving it, as the vendor names it.
    pub instance: &'static str,
    /// Which of that instance's request outputs, in its own numbering.
    pub request: usize,
    /// The level set.
    pub level: Level,
}

/// A rate a model set on one of its instance's clock outputs, in the instance's own numbering.
///
/// A clock is what a tree feeds a peripheral that counts: not a level but a rate, and one the reader keeps
/// time against, so a change re-bases what the reader had counted rather than reinterpreting it. The
/// description says which instance runs on which output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ClockChange {
    /// The instance driving it, as the vendor names it.
    pub instance: &'static str,
    /// Which of that instance's clock outputs, in its own numbering.
    pub output: usize,
    /// The rate from this instant on, where zero is a clock that has stopped.
    pub hz: u64,
}

/// A requested access: a bus or memory access one model asked the runtime to make on its behalf.
///
/// A model may not reach another model: it would be a second borrow of the bus inside a call, and the
/// order of the effects would stop being the description's. So it asks, the runtime performs the access
/// through the ordinary path once the call has returned, and the answer comes back to
/// [`Device::on_access`] carrying the model's own `token`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) struct PendingAccess {
    /// The instant the model asked for it, which is the instant it is made at: a settle is the part
    /// reaching its next steady state and not time passing, so every effect an event or an access sets
    /// off carries that one's instant however long the chain runs.
    pub(crate) at: VirtualNanos,
    /// The slot that asked, so the answer goes back to it.
    pub(crate) owner: usize,
    /// The model's own tag, returned with the answer. It means nothing to the runtime.
    pub(crate) token: u64,
    /// Read or write.
    pub(crate) kind: AccessKind,
    /// The guest address, which the runtime resolves to a peripheral or to memory.
    pub(crate) address: u64,
    /// The access width.
    pub(crate) width: Width,
    /// The value to write, ignored on a read.
    pub(crate) value: u64,
}

/// A level a model set on one of its instance's interrupts, numbered as the part numbers it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct InterruptChange {
    /// The instance, as the vendor names it.
    pub instance: &'static str,
    /// The interrupt number from the instance's table.
    pub interrupt: u16,
    /// The level set.
    pub level: Level,
}

/// A level an interrupt controller on the part drove one of the core's lines to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LineChange {
    /// The core's line.
    pub line: InterruptLine,
    /// The level driven.
    pub level: Level,
}

/// A logic level, of an interrupt line or a pin, held until changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum Level {
    /// Asserted.
    High,
    /// Released, the level of every line and pin before anything drives it.
    #[default]
    Low,
}

impl From<bool> for Level {
    fn from(high: bool) -> Self {
        if high { Self::High } else { Self::Low }
    }
}

impl std::ops::Not for Level {
    type Output = Self;

    fn not(self) -> Self {
        match self {
            Self::High => Self::Low,
            Self::Low => Self::High,
        }
    }
}

/// A model with its layout erased, which is how the runtime holds one it is calling without knowing
/// which model it is. Nothing downcasts back: an MCU reaches its models by field, so the concrete
/// type is never lost in the first place and never has to be recovered.
pub trait ErasedDevice {
    /// The register layout this model was written for, which is what says it is answering for the
    /// right instance. It survives the erasure because it is the one thing about the model's type the
    /// runtime has to know.
    fn layout(&self) -> &'static [RegisterSpec];

    /// Answers a read of the register in `row`, or `None` to serve the register file's value.
    fn read(
        &mut self,
        row: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) -> Option<u64>;
    /// What a read of the register in `row` would answer at `now`, with nothing changed, or `None`
    /// for the register file's value. See [`Device::peek`].
    fn peek(&self, _row: usize, _registers: &RegisterFile, _now: VirtualNanos) -> Option<u64> {
        None
    }
    /// Reacts to a write of the register in `row`, with what landed.
    fn write(
        &mut self,
        row: usize,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    );
    /// Reacts to an event this model scheduled, at its instant. See [`Device::on_event`].
    fn on_event(
        &mut self,
        event: EventId,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    );
    /// Reacts to a request another instance drives. See [`Device::on_request`].
    fn on_request(
        &mut self,
        request: RequestChange,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    );
    /// Takes a change of an interrupt another instance drives. See [`Device::on_interrupt`].
    fn on_interrupt(
        &mut self,
        change: InterruptChange,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        let _ = (change, registers, context);
    }
    /// Takes a change of rate of the clock this instance runs on. See [`Device::on_clock`].
    fn on_clock(&mut self, hz: u64, registers: &mut RegisterFile, context: &mut DeviceContext<'_>);
    /// Looks outside at a stop. See [`Device::poll`].
    fn poll(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>);
    /// The part restarted. See [`Device::reset`].
    fn reset(&mut self);
    /// Takes the answer to an access this model asked for. See [`Device::on_access`].
    fn on_access(
        &mut self,
        token: u64,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    );
    /// Takes the news that an access this model asked for was refused. See [`Device::on_refused`].
    fn on_refused(
        &mut self,
        token: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    );
    /// Answers a read of `width` at `offset` into a [`Window`](crate::soc::Window), for the model of
    /// one. A model of registers is never asked, and answers zero.
    fn read_window(&mut self, offset: u64, width: Width, context: &mut DeviceContext<'_>) -> u64 {
        let _ = (offset, width, context);
        0
    }
    /// Takes a write of `value` as `width` at `offset` into a window. See
    /// [`ErasedDevice::read_window`].
    fn write_window(
        &mut self,
        offset: u64,
        width: Width,
        value: u64,
        context: &mut DeviceContext<'_>,
    ) {
        let _ = (offset, width, value, context);
    }
    /// What a read at `offset` into a window would answer at `now`, with nothing changed, or
    /// `None` where the model can't say without changing something. See [`Device::peek`].
    fn peek_window(&self, offset: u64, width: Width, now: VirtualNanos) -> Option<u64> {
        let _ = (offset, width, now);
        None
    }
}

impl<D: Device + 'static> ErasedDevice for D {
    fn layout(&self) -> &'static [RegisterSpec] {
        Device::layout(self)
    }

    fn read(
        &mut self,
        row: usize,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) -> Option<u64> {
        D::Register::from_index(row)
            .and_then(|register| Device::read(self, register, registers, context))
    }

    fn peek(&self, row: usize, registers: &RegisterFile, now: VirtualNanos) -> Option<u64> {
        D::Register::from_index(row)
            .and_then(|register| Device::peek(self, register, registers, now))
    }

    fn write(
        &mut self,
        row: usize,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        if let Some(register) = D::Register::from_index(row) {
            Device::write(self, register, value, registers, context);
        }
    }

    fn on_event(
        &mut self,
        event: EventId,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        Device::on_event(self, event, registers, context);
    }

    fn on_request(
        &mut self,
        request: RequestChange,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        Device::on_request(self, request, registers, context);
    }

    fn on_interrupt(
        &mut self,
        change: InterruptChange,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        Device::on_interrupt(self, change, registers, context);
    }

    fn on_clock(&mut self, hz: u64, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        Device::on_clock(self, hz, registers, context);
    }

    fn on_access(
        &mut self,
        token: u64,
        value: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        Device::on_access(self, token, value, registers, context);
    }

    fn on_refused(
        &mut self,
        token: u64,
        registers: &mut RegisterFile,
        context: &mut DeviceContext<'_>,
    ) {
        Device::on_refused(self, token, registers, context);
    }

    fn poll(&mut self, registers: &mut RegisterFile, context: &mut DeviceContext<'_>) {
        Device::poll(self, registers, context);
    }

    fn reset(&mut self) {
        Device::reset(self);
    }
}

/// The values of one instance's registers, with reset, access rules, and write-modify arithmetic applied for the model.
///
/// Rows follow the instance's table. Registers the vendor declares as alternates of one another
/// share one offset and one value. Each row is a view of it with its own access rules. A model
/// reads and writes through [`RegisterFile::get`] and [`RegisterFile::set`] as the hardware would,
/// with no rules applied. The bus goes through the rules.
#[derive(Debug, Clone)]
pub struct RegisterFile {
    table: &'static [RegisterSpec],
    /// The rows by ascending offset, which [`RegisterFile::row_covering`] partitions on. A layout's
    /// index names a row, and a part's correction can move a register without moving its row.
    by_offset: Box<[usize]>,
    /// The storage slot each row reads and writes. Alternates share one.
    slot_of_row: Vec<usize>,
    reset_values: Vec<u64>,
    values: Vec<u64>,
    written_once: Vec<bool>,
    /// An SoC's correction of a row's write rule, for its register and every field in it.
    corrected_rules: Vec<Option<WriteModify>>,
    /// An SoC's correction of one field's shape, replacing it whole. `Peripheral::registers` stays the
    /// vendor's table, since that is what a model's own layout is checked against, so a correction here
    /// is the only place the field's true shape lives.
    corrected_fields: Vec<Option<Box<[FieldSpec]>>>,
}

store!(RegisterFile {
    values: [values, written_once],
    parts: [],
    built: [
        table,
        by_offset,
        slot_of_row,
        reset_values,
        corrected_rules,
        corrected_fields
    ],
});

impl RegisterFile {
    pub(crate) fn new(table: &'static [RegisterSpec]) -> Self {
        let slot_of_row: Vec<usize> = table
            .iter()
            .map(|register| {
                table
                    .iter()
                    .position(|earlier| earlier.offset == register.offset)
                    .unwrap_or_default()
            })
            .collect();
        let reset_values: Vec<u64> = table.iter().map(|register| register.reset).collect();
        let mut by_offset: Box<[usize]> = (0..table.len()).collect();
        by_offset.sort_by_key(|&row| table[row].offset);
        Self {
            table,
            by_offset,
            slot_of_row,
            values: reset_values.clone(),
            reset_values,
            written_once: vec![false; table.len()],
            corrected_rules: vec![None; table.len()],
            corrected_fields: vec![None; table.len()],
        }
    }

    /// Makes `rule` the write rule of a row's register and of every field in it.
    pub(crate) fn correct_write(&mut self, row: usize, rule: WriteModify) {
        self.corrected_rules[row] = Some(rule);
    }

    /// The write rule of a row's register, after any correction.
    pub(crate) fn write_rule(&self, row: usize) -> WriteModify {
        self.corrected_rules[row].unwrap_or(self.table[row].write)
    }

    /// Replaces the field named `name` of a row with `corrected`, whole.
    pub(crate) fn correct_field(&mut self, row: usize, name: &'static str, corrected: FieldSpec) {
        let mut fields = self.fields(row).to_vec();
        for field in &mut fields {
            if field.name == name {
                *field = corrected;
            }
        }
        self.corrected_fields[row] = Some(fields.into_boxed_slice());
    }

    /// Adds `field` to a row's declared shape, for a field the vendor's table leaves out entirely.
    pub(crate) fn declare_field(&mut self, row: usize, field: &'static FieldSpec) {
        let mut fields = self.fields(row).to_vec();
        fields.push(*field);
        self.corrected_fields[row] = Some(fields.into_boxed_slice());
    }

    /// The fields of a row, with any [`crate::soc::Builder::field`] correction and any
    /// [`crate::soc::Builder::declare`]d field folded in, for anything outside the crate asking: the
    /// generated table alone is the vendor's and carries neither. A model's own field it never hands
    /// to [`crate::soc::Builder::declare`] is not here either, since nothing but the model's source
    /// carries that one.
    #[must_use]
    pub fn fields(&self, row: usize) -> &[FieldSpec] {
        self.corrected_fields[row]
            .as_deref()
            .unwrap_or(self.table[row].fields)
    }

    pub(crate) fn correct_reset(&mut self, row: usize, value: u64) {
        let slot = self.slot_of_row[row];
        self.reset_values[slot] = value;
        self.values[slot] = value;
    }

    /// Returns every register to its reset value and forgets which were written once.
    pub fn reset(&mut self) {
        self.values.clone_from(&self.reset_values);
        self.written_once.fill(false);
    }

    /// The value a register holds.
    pub fn get<L: Layout>(&self, register: L) -> u64 {
        self.get_row(register.index())
    }

    /// Sets a register as the hardware would, bypassing the bus rules.
    pub fn set<L: Layout>(&mut self, register: L, value: u64) {
        self.values[self.slot_of_row[register.index()]] = value & register.spec().width.mask();
    }

    /// Puts the masked bits of a register back to `kept`, for a model correcting a field its
    /// description file types more permissively than the part's documentation does. The bus
    /// enforces the table it was given and any correction the part made with
    /// [`crate::soc::Builder::field`], so where neither is right the model is the only thing that
    /// can be.
    pub fn restore<L: Layout>(&mut self, register: L, mask: u64, kept: u64) {
        let value = self.get(register);
        self.set(register, (value & !mask) | (kept & mask));
    }

    /// Writes a register as the bus would, honoring its access and write rules: for a model that forwards a
    /// write to another register, as one with a burst window over its own registers does.
    pub fn write_over_bus<L: Layout>(&mut self, register: L, written: u64) {
        self.bus_write(register.index(), written);
    }

    pub(crate) fn get_row(&self, row: usize) -> u64 {
        self.values[self.slot_of_row[row]]
    }

    /// The row of the register covering an offset whose access `allows` the direction, or the first covering row.
    #[inline]
    pub(crate) fn row_covering(&self, offset: u32, allows: fn(Access) -> bool) -> Option<usize> {
        let first_past = self
            .by_offset
            .partition_point(|&row| self.table[row].offset <= offset);
        let mut first = first_past;
        while first > 0 && self.table[self.by_offset[first - 1]].end() > offset {
            first -= 1;
        }
        let covering = &self.by_offset[first..first_past];
        covering
            .iter()
            .copied()
            .find(|&row| allows(self.table[row].access))
            .or_else(|| covering.first().copied())
    }

    /// A read over the bus: honors access, then applies the read actions.
    pub(crate) fn bus_read(&mut self, row: usize) -> u64 {
        let register = &self.table[row];
        if !register.access.is_readable() {
            return 0;
        }
        let register_read = register.read;
        let slot = self.slot_of_row[row];
        let value = self.values[slot];
        let mut after = register_read.apply(value, register.width.mask());
        for field in self
            .fields(row)
            .iter()
            .filter(|field| field.read != register_read)
        {
            after =
                (after & !field.mask()) | (field.read.apply(value, field.mask()) & field.mask());
        }
        self.values[slot] = after;
        value
    }

    /// What [`RegisterFile::bus_read`] would answer, with no read action taken.
    pub(crate) fn bus_peek(&self, row: usize) -> u64 {
        if self.table[row].access.is_readable() {
            self.get_row(row)
        } else {
            0
        }
    }

    /// A write over the bus: honors access, then applies the write-modify arithmetic per register and per field.
    pub(crate) fn bus_write(&mut self, row: usize, written: u64) {
        let register = &self.table[row];
        if !register.access.is_writable()
            || (register.access.is_write_once() && self.written_once[row])
        {
            return;
        }
        let register_write = register.write;
        let width_mask = register.width.mask();
        self.written_once[row] = true;
        let slot = self.slot_of_row[row];
        let old = self.values[slot];
        let corrected = self.corrected_rules[row];
        let mut landed = corrected.unwrap_or(register_write).apply(old, written);
        for field in self.fields(row) {
            let field_bits = if field.access.is_writable() {
                corrected.unwrap_or(field.write).apply(old, written)
            } else {
                old
            };
            landed = (landed & !field.mask()) | (field_bits & field.mask());
        }
        self.values[slot] = landed & width_mask;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::soc::{FieldSpec, ReadAction, Width, WriteModify};

    const fn register(
        name: &'static str,
        offset: u32,
        access: Access,
        read: ReadAction,
    ) -> RegisterSpec {
        RegisterSpec {
            name,
            offset,
            width: Width::W16,
            reset: 0xBEEF,
            access,
            read,
            write: WriteModify::None,
            fields: &[],
        }
    }

    const FLAG: FieldSpec = FieldSpec {
        name: "FLAG",
        bit: 0,
        width: 1,
        access: Access::ReadOnly,
        read: ReadAction::Clear,
        write: WriteModify::None,
    };

    static REGISTERS: [RegisterSpec; 4] = [
        register("PLAIN", 0x0, Access::ReadWrite, ReadAction::None),
        register("ONCE", 0x2, Access::ReadWriteOnce, ReadAction::None),
        register("POP", 0x4, Access::ReadOnly, ReadAction::Clear),
        RegisterSpec {
            fields: &[FLAG],
            ..register("STATUS", 0x6, Access::ReadWrite, ReadAction::None)
        },
    ];

    #[derive(Debug, Clone, Copy)]
    enum Register {
        Plain,
        Once,
        Pop,
        Status,
    }

    impl Layout for Register {
        const REGISTERS: &'static [RegisterSpec] = &REGISTERS;
        fn from_index(index: usize) -> Option<Self> {
            [Self::Plain, Self::Once, Self::Pop, Self::Status]
                .get(index)
                .copied()
        }
        fn index(self) -> usize {
            self as usize
        }
    }

    #[test]
    fn write_modify_arithmetic_and_its_neutral_value() {
        assert_eq!(WriteModify::OneToClear.apply(0b1111, 0b0101), 0b1010);
        assert_eq!(WriteModify::OneToSet.apply(0b1000, 0b0001), 0b1001);
        assert_eq!(WriteModify::OneToToggle.apply(0b1100, 0b0110), 0b1010);
        assert_eq!(WriteModify::ZeroToClear.apply(0b1111, 0b0101), 0b0101);
        assert_eq!(WriteModify::ZeroToSet.apply(0, 0b1110) & 0xF, 0b0001);
        assert_eq!(
            WriteModify::ZeroToToggle.apply(0b1111, 0b1110) & 0xF,
            0b1110
        );
        assert_eq!(WriteModify::Clear.apply(0b1111, 0b0101), 0);
        assert_eq!(WriteModify::Modify.apply(0b1111, 0b0101), 0b1111);
        for modify in [
            WriteModify::None,
            WriteModify::OneToClear,
            WriteModify::OneToSet,
            WriteModify::ZeroToClear,
            WriteModify::ZeroToSet,
        ] {
            assert_eq!(
                modify.apply(0xA5, modify.neutral(0xA5)) & 0xFF,
                0xA5,
                "{modify:?}"
            );
        }
    }

    #[test]
    fn set_masks_to_the_register_width() {
        let mut registers = RegisterFile::new(&REGISTERS);
        registers.set(Register::Plain, 0x1_2345);
        assert_eq!(registers.get(Register::Plain), 0x2345);
    }

    #[test]
    fn reset_restores_values_and_forgets_first_writes() {
        let mut registers = RegisterFile::new(&REGISTERS);
        registers.bus_write(Register::Once.index(), 1);
        registers.bus_write(Register::Once.index(), 2);
        assert_eq!(registers.get(Register::Once), 1);
        registers.reset();
        assert_eq!(registers.get(Register::Once), 0xBEEF);
        registers.bus_write(Register::Once.index(), 3);
        assert_eq!(
            registers.get(Register::Once),
            3,
            "the first write after reset lands again"
        );
    }

    #[test]
    fn a_read_only_register_ignores_writes_and_clears_on_read() {
        let mut registers = RegisterFile::new(&REGISTERS);
        registers.bus_write(Register::Pop.index(), 0);
        assert_eq!(registers.bus_read(Register::Pop.index()), 0xBEEF);
        assert_eq!(registers.bus_read(Register::Pop.index()), 0);
    }

    #[test]
    fn a_field_may_clear_on_read_while_its_register_does_not() {
        let mut registers = RegisterFile::new(&REGISTERS);
        assert_eq!(registers.bus_read(Register::Status.index()), 0xBEEF);
        assert_eq!(registers.get(Register::Status), 0xBEEE, "only FLAG cleared");
    }

    #[test]
    fn a_peek_answers_what_a_read_would_and_takes_no_read_action() {
        static HIDDEN: [RegisterSpec; 1] =
            [register("KEY", 0x0, Access::WriteOnly, ReadAction::None)];
        let mut registers = RegisterFile::new(&REGISTERS);
        for register in [Register::Pop, Register::Status] {
            assert_eq!(registers.bus_peek(register.index()), 0xBEEF);
            assert_eq!(registers.bus_peek(register.index()), 0xBEEF, "still");
            assert_eq!(registers.bus_read(register.index()), 0xBEEF);
        }
        assert_eq!(
            registers.bus_peek(Register::Pop.index()),
            0,
            "the read cleared it"
        );
        let mut hidden = RegisterFile::new(&HIDDEN);
        assert_eq!(
            (hidden.bus_peek(0), hidden.bus_read(0)),
            (0, 0),
            "a register the bus can't read"
        );
    }

    #[test]
    fn rows_are_found_by_the_offset_they_cover() {
        let registers = RegisterFile::new(&REGISTERS);
        assert_eq!(registers.row_covering(0x2, Access::is_readable), Some(1));
        assert_eq!(
            registers.row_covering(0x3, Access::is_readable),
            Some(1),
            "the second byte of ONCE"
        );
        assert_eq!(registers.row_covering(0x8, Access::is_readable), None);
    }

    /// A row is found by its offset whatever order the table puts it in.
    #[test]
    fn rows_are_found_by_offset_in_any_order() {
        static BACKWARDS: [RegisterSpec; 3] = [
            register("HIGH", 0x4, Access::ReadWrite, ReadAction::None),
            register("MIDDLE", 0x2, Access::ReadWrite, ReadAction::None),
            register("LOW", 0x0, Access::ReadWrite, ReadAction::None),
        ];
        let registers = RegisterFile::new(&BACKWARDS);
        for (offset, row) in [(0x0, 2), (0x1, 2), (0x2, 1), (0x4, 0), (0x5, 0)] {
            assert_eq!(
                registers.row_covering(offset, Access::is_readable),
                Some(row),
                "{offset:#x}"
            );
        }
        assert_eq!(registers.row_covering(0x6, Access::is_readable), None);
    }
}