rigless 0.0.4

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; needs the rigless-sidecar package from rigless-labs/qemu
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: Apache-2.0
//! The static description of a system on chip, and the [`Bus`] that gives its addresses meaning.
//!
//! The description is what `rigless svd generate` emits from the vendor's SVD: a [`Cpu`], every
//! [`Peripheral`] instance at its address, and one [`RegisterSpec`] table per layout, with a
//! [`Layout`] enum naming each table's registers. A hand-written memory map of [`Region`]s
//! completes it. [`Bus::builder`] assembles all of that with the SoC's corrections, reset values
//! and write rules both, checks it once, and produces a [`Bus`].
//!
//! **A bus owns no models.** It decodes an address to a slot, holds each slot's [`RegisterFile`],
//! and carries the event queue and the interrupt changes. The models are fields of the MCU that
//! has them, and [`crate::mcu::Mcu`] is what joins the two: it hands the bus and the model in one
//! slot to the runtime, borrowed apart, so a model is reached by a field and never by a name.
//!
//! Nothing here knows which processor family the SoC belongs to: addresses and values are
//! 64-bit, and a [`Cpu`] is a name, an FPU flag, and an interrupt count.
//!
//! A model raises its interrupt by position in its instance's table, `context.raise(UPDATE)` with
//! `const UPDATE: usize = 0`, because a layout is shared by every instance built on it and only the
//! instance knows its number; the bus resolves the position and reports the change as the instance's
//! name, the number, and the level. A position the table does not list is a bug in the model and
//! panics with the instance's name.

#[cfg(feature = "stm32f427")]
pub mod stm32f427;

use std::fmt;

use crate::device::{DeviceContext, InterruptChange, RegisterFile};
use crate::time::{EventId, EventQueue, VirtualNanos};

/// The processor core as the SVD describes it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cpu {
    /// The core name as the vendor spells it.
    pub name: &'static str,
    /// Whether the core has a floating-point unit.
    pub fpu: bool,
    /// Number of external interrupt lines the interrupt controller has.
    pub interrupt_lines: u16,
}

/// One peripheral instance at its address.
///
/// Instances the SVD derives from a sibling share that sibling's table, so every instance of one
/// kind points at one generated `REGISTERS`. An SoC module corrects an instance the vendor's file
/// got wrong with struct update syntax: `Peripheral { interrupts: &[87], ..generated::AN_INSTANCE }`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Peripheral {
    /// The instance name as the vendor spells it, such as `SPI1`.
    pub name: &'static str,
    /// Absolute address of the first register.
    pub base: u64,
    /// Bytes the instance occupies on the bus.
    pub size: u64,
    /// Interrupt lines the instance raises, ascending.
    pub interrupts: &'static [u16],
    /// The register table, ordered by offset.
    pub registers: &'static [RegisterSpec],
}

impl Peripheral {
    /// Whether the address falls inside the instance.
    pub const fn contains(&self, address: u64) -> bool {
        address >= self.base && address < self.base + self.size
    }
}

/// One register of a table: where it is, what it holds after reset, and how the bus may treat it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RegisterSpec {
    /// The register name as the vendor spells it.
    pub name: &'static str,
    /// Offset from the instance base.
    pub offset: u32,
    /// Width on the bus.
    pub width: Width,
    /// Value after reset.
    pub reset: u64,
    /// Which directions the bus allows.
    pub access: Access,
    /// What a read does to the register.
    pub read: ReadAction,
    /// What arithmetic a write performs before the value lands.
    pub write: WriteModify,
    /// The bit fields, ordered by position.
    pub fields: &'static [FieldSpec],
}

impl RegisterSpec {
    /// One past the last byte of the register, as an offset from the instance base.
    pub const fn end(&self) -> u32 {
        self.offset + self.width.bytes()
    }
}

/// One bit field of a register.
///
/// The generator emits one constant per field, so a model reads a bit by name:
/// `cr1::SPE.is_set(value)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FieldSpec {
    /// The field name as the vendor spells it.
    pub name: &'static str,
    /// Position of the least significant bit.
    pub bit: u8,
    /// Width in bits.
    pub width: u8,
    /// Which directions the bus allows; the register's unless the SVD says otherwise.
    pub access: Access,
    /// What a read does to the field; the register's unless the SVD says otherwise.
    pub read: ReadAction,
    /// What arithmetic a write performs; the register's unless the SVD says otherwise.
    pub write: WriteModify,
}

impl FieldSpec {
    /// The bits the field occupies within the register.
    pub const fn mask(&self) -> u64 {
        if self.width >= Width::W64.bits() {
            u64::MAX
        } else {
            ((1u64 << self.width) - 1) << self.bit
        }
    }

    /// The field's value within a register value.
    pub const fn get(&self, register_value: u64) -> u64 {
        (register_value & self.mask()) >> self.bit
    }

    /// The register value with this field replaced.
    pub const fn set(&self, register_value: u64, field_value: u64) -> u64 {
        (register_value & !self.mask()) | ((field_value << self.bit) & self.mask())
    }

    /// Whether any bit of the field is set in the register value.
    pub const fn is_set(&self, register_value: u64) -> bool {
        register_value & self.mask() != 0
    }
}

/// Width of a register, or of a bus access, in bits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Width {
    /// Eight bits.
    W8,
    /// Sixteen bits.
    W16,
    /// Thirty-two bits.
    W32,
    /// Sixty-four bits.
    W64,
}

impl Width {
    /// The width in bits.
    pub const fn bits(self) -> u8 {
        match self {
            Self::W8 => 8,
            Self::W16 => 16,
            Self::W32 => 32,
            Self::W64 => 64,
        }
    }

    /// The width in bytes.
    pub const fn bytes(self) -> u32 {
        self.bits() as u32 / 8
    }

    /// A mask of the bits a value of this width holds.
    pub const fn mask(self) -> u64 {
        match self {
            Self::W64 => u64::MAX,
            narrower => (1u64 << narrower.bits()) - 1,
        }
    }
}

/// Which directions the bus allows, as the CMSIS-SVD `access` element names them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Access {
    /// Reads return the value; writes are ignored.
    ReadOnly,
    /// Writes land; reads return zero.
    WriteOnly,
    /// Both directions.
    ReadWrite,
    /// Only the first write after reset lands; reads return zero.
    WriteOnce,
    /// Only the first write after reset lands; reads return the value.
    ReadWriteOnce,
}

impl Access {
    /// Whether the bus may read the value.
    pub const fn is_readable(self) -> bool {
        !matches!(self, Self::WriteOnly | Self::WriteOnce)
    }

    /// Whether the bus may write the value, at least once.
    pub const fn is_writable(self) -> bool {
        !matches!(self, Self::ReadOnly)
    }

    /// Whether only the first write after reset lands.
    pub const fn is_write_once(self) -> bool {
        matches!(self, Self::WriteOnce | Self::ReadWriteOnce)
    }
}

/// What a read does to a register, as the CMSIS-SVD `readAction` element names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadAction {
    /// Nothing.
    None,
    /// The register clears.
    Clear,
    /// The register sets.
    Set,
    /// The register changes in a way only the model knows.
    Modify,
    /// Another register changes.
    ModifyExternal,
}

impl ReadAction {
    /// The value the register holds after a read of `value`, within `mask`.
    pub const fn apply(self, value: u64, mask: u64) -> u64 {
        match self {
            Self::Clear => value & !mask,
            Self::Set => value | mask,
            Self::None | Self::Modify | Self::ModifyExternal => value,
        }
    }
}

/// What arithmetic a write performs before the value lands, as the CMSIS-SVD `modifiedWriteValues` element names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WriteModify {
    /// The written value lands.
    None,
    /// Written ones clear their bits.
    OneToClear,
    /// Written ones set their bits.
    OneToSet,
    /// Written ones toggle their bits.
    OneToToggle,
    /// Written zeros clear their bits.
    ZeroToClear,
    /// Written zeros set their bits.
    ZeroToSet,
    /// Written zeros toggle their bits.
    ZeroToToggle,
    /// Any write clears the register.
    Clear,
    /// Any write sets the register.
    Set,
    /// Any write changes the register in a way only the model knows.
    Modify,
}

impl WriteModify {
    /// The value that lands when `written` arrives over `old`.
    pub const fn apply(self, old: u64, written: u64) -> u64 {
        match self {
            Self::None => written,
            Self::OneToClear => old & !written,
            Self::OneToSet => old | written,
            Self::OneToToggle => old ^ written,
            Self::ZeroToClear => old & written,
            Self::ZeroToSet => old | !written,
            Self::ZeroToToggle => old ^ !written,
            Self::Clear => 0,
            Self::Set => u64::MAX,
            Self::Modify => old,
        }
    }

    /// The written value that leaves `old` unchanged, for the lanes a narrow access does not touch.
    pub const fn neutral(self, old: u64) -> u64 {
        match self {
            Self::OneToClear | Self::OneToSet | Self::OneToToggle => 0,
            Self::ZeroToClear | Self::ZeroToSet | Self::ZeroToToggle => u64::MAX,
            Self::None | Self::Clear | Self::Set | Self::Modify => old,
        }
    }
}

/// A register table's names as a type, so a model matches on registers instead of strings.
///
/// The generator emits one enum implementing this per table; a variant's index is its row in
/// [`Layout::REGISTERS`].
pub trait Layout: Copy + fmt::Debug {
    /// The table this layout names.
    const REGISTERS: &'static [RegisterSpec];

    /// The register at this row of the table.
    fn from_index(index: usize) -> Option<Self>;

    /// This register's row in the table.
    fn index(self) -> usize;

    /// This register's row of the table.
    fn spec(self) -> &'static RegisterSpec {
        &Self::REGISTERS[self.index()]
    }
}

/// What a memory region holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RegionKind {
    /// Code and constant data, loaded from the firmware image.
    Flash,
    /// Read-write memory.
    Ram,
    /// Vendor read-only data such as the unique device ID.
    System,
}

/// One memory region of the SoC.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Region {
    /// The region name, such as `sram`.
    pub name: &'static str,
    /// Absolute address of the first byte.
    pub base: u64,
    /// Size in bytes.
    pub size: u64,
    /// What the region holds.
    pub kind: RegionKind,
}

impl Region {
    /// A flash region.
    pub const fn flash(name: &'static str, base: u64, size: u64) -> Self {
        Self {
            name,
            base,
            size,
            kind: RegionKind::Flash,
        }
    }

    /// A RAM region.
    pub const fn ram(name: &'static str, base: u64, size: u64) -> Self {
        Self {
            name,
            base,
            size,
            kind: RegionKind::Ram,
        }
    }

    /// A system memory region.
    pub const fn system(name: &'static str, base: u64, size: u64) -> Self {
        Self {
            name,
            base,
            size,
            kind: RegionKind::System,
        }
    }
}

/// Why an SoC description does not hold together.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Two memory regions share addresses.
    #[error("memory regions {lower} and {upper} overlap")]
    OverlappingRegions {
        /// The region with the lower base.
        lower: &'static str,
        /// The region that starts inside it.
        upper: &'static str,
    },
    /// Two peripheral instances share addresses.
    #[error("peripheral instances {lower} and {upper} overlap")]
    OverlappingInstances {
        /// The instance with the lower base.
        lower: &'static str,
        /// The instance that starts inside it.
        upper: &'static str,
    },
    /// An instance raises an interrupt line the CPU does not have.
    #[error("{instance} raises interrupt {line} but the CPU has {lines} lines")]
    InterruptOutOfRange {
        /// The instance.
        instance: &'static str,
        /// The interrupt line.
        line: u16,
        /// Lines the CPU has.
        lines: u16,
    },
    /// A binding or correction names an instance the SoC does not have.
    #[error("{instance} is not an instance of this SoC")]
    UnknownInstance {
        /// The name given.
        instance: &'static str,
    },
    /// A correction names a register the instance does not have.
    #[error("{instance} has no register {register}")]
    UnknownRegister {
        /// The instance.
        instance: &'static str,
        /// The name given.
        register: &'static str,
    },
    /// A corrected reset value has bits beyond the register's width.
    #[error("reset value {value:#x} does not fit {instance}.{register}")]
    ResetTooWide {
        /// The instance.
        instance: &'static str,
        /// The register.
        register: &'static str,
        /// The value given.
        value: u64,
    },
    /// A device written for one register layout was bound to an instance of another.
    #[error("{instance} does not have the register layout the device was written for")]
    LayoutMismatch {
        /// The instance.
        instance: &'static str,
    },
    /// Two devices were bound to one instance.
    #[error("{instance} is bound twice")]
    BoundTwice {
        /// The instance.
        instance: &'static str,
    },
}

/// Why a bus access could not complete.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Fault {
    /// No register covers the address.
    #[error("no register at {address:#x}")]
    Unmapped {
        /// The address accessed.
        address: u64,
    },
    /// The access runs past the end of the register that covers the address.
    #[error("a {}-bit access at {address:#x} runs past its register", width.bits())]
    Misaligned {
        /// The address accessed.
        address: u64,
        /// The width of the access.
        width: Width,
    },
}

/// One peripheral instance on the bus: where it answers, and what it holds. The model that gives it
/// behaviour is a field of the MCU, not a box in here.
pub struct Slot {
    peripheral: Peripheral,
    registers: RegisterFile,
}

impl Slot {
    /// The instance this slot answers for.
    #[must_use]
    pub fn peripheral(&self) -> &Peripheral {
        &self.peripheral
    }

    /// What this instance holds.
    #[must_use]
    pub fn registers(&self) -> &RegisterFile {
        &self.registers
    }

    /// What this instance holds, for the model that owns it.
    pub fn registers_mut(&mut self) -> &mut RegisterFile {
        &mut self.registers
    }
}

impl fmt::Debug for Slot {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Slot")
            .field("peripheral", &self.peripheral.name)
            .field("registers", &self.registers)
            .finish()
    }
}

/// A named span of addresses, for the overlap checks.
struct Extent {
    name: &'static str,
    base: u64,
    size: u64,
}

impl Extent {
    const fn end(&self) -> u64 {
        self.base.saturating_add(self.size)
    }
}

/// Assembles a bus from its description and the SoC's corrections, checking everything once in [`Builder::build`].
#[must_use = "a builder does nothing until built"]
pub struct Builder {
    cpu: Cpu,
    memory: &'static [Region],
    peripherals: Vec<Peripheral>,
    reset_corrections: Vec<ResetCorrection>,
    write_corrections: Vec<WriteCorrection>,
}

struct ResetCorrection {
    instance: &'static str,
    register: &'static str,
    value: u64,
}

struct WriteCorrection {
    instance: &'static str,
    register: &'static str,
    rule: WriteModify,
}

impl fmt::Debug for Builder {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Builder")
            .field("cpu", &self.cpu)
            .field("reset_corrections", &self.reset_corrections.len())
            .field("write_corrections", &self.write_corrections.len())
            .finish_non_exhaustive()
    }
}

impl Builder {
    /// Overrides a reset value where the SVD disagrees with the vendor's documentation of the SoC.
    pub fn reset(mut self, instance: &'static str, register: &'static str, value: u64) -> Self {
        self.reset_corrections.push(ResetCorrection {
            instance,
            register,
            value,
        });
        self
    }

    /// Overrides the write rule of a register and of every field in it where the SVD disagrees with the
    /// vendor's documentation of the SoC, a status register whose flags clear on a written zero for one.
    pub fn write_modify(
        mut self,
        instance: &'static str,
        register: &'static str,
        rule: WriteModify,
    ) -> Self {
        self.write_corrections.push(WriteCorrection {
            instance,
            register,
            rule,
        });
        self
    }

    /// Checks the description and produces the bus, naming what is at fault otherwise.
    pub fn build(self) -> Result<Bus, Error> {
        let regions = self.memory.iter().map(|region| Extent {
            name: region.name,
            base: region.base,
            size: region.size,
        });
        if let Some((lower, upper)) = first_overlap(regions) {
            return Err(Error::OverlappingRegions { lower, upper });
        }
        let spans = self.peripherals.iter().map(|peripheral| Extent {
            name: peripheral.name,
            base: peripheral.base,
            size: peripheral.size,
        });
        if let Some((lower, upper)) = first_overlap(spans) {
            return Err(Error::OverlappingInstances { lower, upper });
        }
        check_interrupts(&self.peripherals, self.cpu.interrupt_lines)?;

        let mut slots: Vec<Slot> = self
            .peripherals
            .into_iter()
            .map(|peripheral| Slot {
                peripheral,
                registers: RegisterFile::new(peripheral.registers),
            })
            .collect();
        slots.sort_by_key(|slot| slot.peripheral.base);

        for correction in self.reset_corrections {
            let instance = instance_named(&mut slots, correction.instance)?;
            let (row, register) = instance
                .peripheral
                .registers
                .iter()
                .enumerate()
                .find(|(_, register)| register.name == correction.register)
                .ok_or(Error::UnknownRegister {
                    instance: correction.instance,
                    register: correction.register,
                })?;
            if correction.value & !register.width.mask() != 0 {
                return Err(Error::ResetTooWide {
                    instance: correction.instance,
                    register: correction.register,
                    value: correction.value,
                });
            }
            instance.registers.correct_reset(row, correction.value);
        }

        for correction in self.write_corrections {
            let instance = instance_named(&mut slots, correction.instance)?;
            let row = instance
                .peripheral
                .registers
                .iter()
                .position(|register| register.name == correction.register)
                .ok_or(Error::UnknownRegister {
                    instance: correction.instance,
                    register: correction.register,
                })?;
            instance.registers.correct_write(row, correction.rule);
        }

        Ok(Bus {
            cpu: self.cpu,
            memory: self.memory,
            slots,
            events: EventQueue::default(),
            interrupt_changes: Vec::new(),
        })
    }
}

fn instance_named<'a>(slots: &'a mut [Slot], name: &'static str) -> Result<&'a mut Slot, Error> {
    slots
        .iter_mut()
        .find(|slot| slot.peripheral.name == name)
        .ok_or(Error::UnknownInstance { instance: name })
}

/// The first two spans that share an address, by ascending base.
fn first_overlap(spans: impl Iterator<Item = Extent>) -> Option<(&'static str, &'static str)> {
    let mut sorted: Vec<Extent> = spans.collect();
    sorted.sort_by_key(|span| span.base);
    sorted
        .windows(2)
        .find(|pair| pair[1].base < pair[0].end())
        .map(|pair| (pair[0].name, pair[1].name))
}

fn check_interrupts(peripherals: &[Peripheral], lines: u16) -> Result<(), Error> {
    for peripheral in peripherals {
        if let Some(&line) = peripheral.interrupts.iter().find(|&&line| line >= lines) {
            return Err(Error::InterruptOutOfRange {
                instance: peripheral.name,
                line,
                lines,
            });
        }
    }
    Ok(())
}

/// A checked bus: the CPU, the memory map, and every peripheral instance with its register file.
///
/// It answers where an address lands and what that register holds; it does not answer what the
/// peripheral *does*. That is the model, which is a field of the MCU built on this bus.
#[derive(Debug)]
pub struct Bus {
    cpu: Cpu,
    memory: &'static [Region],
    slots: Vec<Slot>,
    events: EventQueue,
    interrupt_changes: Vec<InterruptChange>,
}

/// How many events one instant may carry before the runtime calls it a model that cannot move time on.
/// Several models legitimately schedule at one instant; none of them needs a thousand.
pub(crate) const SAME_INSTANT_LIMIT: u32 = 1_000;

impl Bus {
    /// Starts assembling a bus from its CPU, memory map, and peripheral instances.
    pub fn builder(
        cpu: Cpu,
        memory: &'static [Region],
        peripherals: impl IntoIterator<Item = Peripheral>,
    ) -> Builder {
        Builder {
            cpu,
            memory,
            peripherals: peripherals.into_iter().collect(),
            reset_corrections: Vec::new(),
            write_corrections: Vec::new(),
        }
    }

    /// Every slot, in address order; the index is what [`crate::mcu::Mcu::split`] dispatches on.
    #[must_use]
    pub fn slots(&self) -> &[Slot] {
        &self.slots
    }

    /// The slot index of the instance called `name`, which an MCU resolves once at construction so
    /// that nothing after it looks a peripheral up by string.
    #[must_use]
    pub fn slot_of(&self, name: &str) -> Option<usize> {
        self.slots
            .iter()
            .position(|slot| slot.peripheral.name == name)
    }

    /// The CPU.
    pub fn cpu(&self) -> Cpu {
        self.cpu
    }

    /// The memory regions.
    pub fn memory(&self) -> &'static [Region] {
        self.memory
    }

    /// Every peripheral instance, by ascending base address.
    pub fn peripherals(&self) -> impl Iterator<Item = &Peripheral> {
        self.slots.iter().map(|slot| &slot.peripheral)
    }

    /// The instance with this name.
    pub fn peripheral(&self, name: &str) -> Option<&Peripheral> {
        self.peripherals()
            .find(|peripheral| peripheral.name == name)
    }

    /// The register file of the instance with this name.
    #[must_use]
    pub fn registers(&self, name: &str) -> Option<&RegisterFile> {
        self.slots
            .iter()
            .find(|slot| slot.peripheral.name == name)
            .map(|slot| &slot.registers)
    }

    /// One slot, for the MCU calling the model that owns it.
    pub(crate) fn slot_mut(&mut self, index: usize) -> &mut Slot {
        &mut self.slots[index]
    }

    /// Where an access lands, or the fault it takes.
    pub(crate) fn locate(
        &self,
        address: u64,
        width: Width,
        allows: fn(Access) -> bool,
    ) -> Result<Located, Fault> {
        let candidates = self
            .slots
            .partition_point(|slot| slot.peripheral.base <= address);
        let Some(index) = candidates.checked_sub(1) else {
            return Err(Fault::Unmapped { address });
        };
        let slot = &self.slots[index];
        if !slot.peripheral.contains(address) {
            return Err(Fault::Unmapped { address });
        }
        let offset = u32::try_from(address - slot.peripheral.base)
            .map_err(|_too_far| Fault::Unmapped { address })?;
        let row = slot
            .registers
            .row_covering(offset, allows)
            .ok_or(Fault::Unmapped { address })?;
        let register = &slot.peripheral.registers[row];
        let byte_in_register = offset - register.offset;
        if byte_in_register + width.bytes() > register.width.bytes() {
            return Err(Fault::Misaligned { address, width });
        }
        Ok(Located {
            slot: index,
            row,
            lane: Lane {
                shift: byte_in_register * u32::from(Width::W8.bits()),
            },
        })
    }

    /// The slot at `index` with a context for the model that owns it, borrowed apart.
    pub(crate) fn call(
        &mut self,
        at: VirtualNanos,
        index: usize,
    ) -> (&mut Slot, DeviceContext<'_>) {
        let Self {
            slots,
            events,
            interrupt_changes,
            ..
        } = self;
        let slot = &mut slots[index];
        let context = DeviceContext::new(at, index, slot.peripheral, events, interrupt_changes);
        (slot, context)
    }

    /// The next event due by `now`, as its id, the slot that scheduled it, and its instant.
    pub(crate) fn pop_due(&mut self, now: VirtualNanos) -> Option<(EventId, usize, VirtualNanos)> {
        self.events.pop_due(now)
    }

    /// The instant of the earliest pending event, which is when the engine next needs to stop.
    #[must_use]
    pub fn next_event(&self) -> Option<VirtualNanos> {
        self.events.next_at()
    }

    /// Takes the interrupt levels the models set since the last drain, in the order they set them.
    pub fn drain_interrupts(&mut self) -> impl Iterator<Item = InterruptChange> + '_ {
        self.interrupt_changes.drain(..)
    }
}

/// Where one bus access lands: the slot, the register row, and the lane inside the register.
pub(crate) struct Located {
    pub(crate) slot: usize,
    pub(crate) row: usize,
    pub(crate) lane: Lane,
}

pub(crate) struct Lane {
    pub(crate) shift: u32,
}