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
// Copyright 2018 Adam Greig
// See LICENSE-APACHE and LICENSE-MIT for license details.

//! This crate contains an MMIO abstraction that uses macros to read,
//! modify, and write fields in registers.
//!
//! See the [README](https://github.com/adamgreig/ral-registers/blob/master/README.md)
//! for further details.

#![no_std]

use core::cell::UnsafeCell;

/// A read-write register of type T.
///
/// Contains one value of type T and provides volatile read/write functions to it.
///
/// # Safety
/// This register should be used where reads and writes to this peripheral register do not
/// lead to memory unsafety. For example, it is a poor choice for a DMA target, but less
/// worrisome for a GPIO output data register.
///
/// Access to this register must be synchronised; if multiple threads (or the main thread and an
/// interrupt service routine) are accessing it simultaneously you may encounter data races.
#[repr(transparent)]
pub struct RWRegister<T> {
    register: UnsafeCell<T>,
}

impl<T: Copy> RWRegister<T> {
    /// Reads the value of the register.
    #[inline(always)]
    pub fn read(&self) -> T {
        unsafe { ::core::ptr::read_volatile(self.register.get()) }
    }

    /// Writes a new value to the register.
    #[inline(always)]
    pub fn write(&self, val: T) {
        unsafe { ::core::ptr::write_volatile(self.register.get(), val) }
    }
}

/// A read-write register of type T, where read/write access is unsafe.
///
/// Contains one value of type T and provides volatile read/write functions to it.
///
/// # Safety
/// This register should be used where reads and writes to this peripheral may invoke
/// undefined behaviour or memory unsafety. For example, any registers you write a memory
/// address into.
///
/// Access to this register must be synchronised; if multiple threads (or the main thread and an
/// interrupt service routine) are accessing it simultaneously you may encounter data races.
#[repr(transparent)]
pub struct UnsafeRWRegister<T> {
    register: UnsafeCell<T>,
}

impl<T: Copy> UnsafeRWRegister<T> {
    /// Reads the value of the register.
    ///
    /// # Safety
    /// Refer to [UnsafeRWRegister]'s Safety section.
    #[inline(always)]
    pub unsafe fn read(&self) -> T {
        ::core::ptr::read_volatile(self.register.get())
    }

    /// Writes a new value to the register.
    ///
    /// # Safety
    /// Refer to [UnsafeRWRegister]'s Safety section.
    #[inline(always)]
    pub unsafe fn write(&self, val: T) {
        ::core::ptr::write_volatile(self.register.get(), val)
    }
}

/// A read-only register of type T.
///
/// Contains one value of type T and provides a volatile read function to it.
///
/// # Safety
/// This register should be used where reads and writes to this peripheral register do not
/// lead to memory unsafety.
///
/// Access to this register must be synchronised; if multiple threads (or the main thread and an
/// interrupt service routine) are accessing it simultaneously you may encounter data races.
#[repr(transparent)]
pub struct RORegister<T> {
    register: UnsafeCell<T>,
}

impl<T: Copy> RORegister<T> {
    /// Reads the value of the register.
    #[inline(always)]
    pub fn read(&self) -> T {
        unsafe { ::core::ptr::read_volatile(self.register.get()) }
    }
}

/// A read-only register of type T, where read access is unsafe.
///
/// Contains one value of type T and provides a volatile read function to it.
///
/// # Safety
/// This register should be used where reads to this peripheral may invoke
/// undefined behaviour or memory unsafety.
///
/// Access to this register must be synchronised; if multiple threads (or the main thread and an
/// interrupt service routine) are accessing it simultaneously you may encounter data races.
#[repr(transparent)]
pub struct UnsafeRORegister<T> {
    register: UnsafeCell<T>,
}

impl<T: Copy> UnsafeRORegister<T> {
    /// Reads the value of the register.
    ///
    /// # Safety
    /// Refer to [UnsafeRWRegister]'s Safety section.
    #[inline(always)]
    pub unsafe fn read(&self) -> T {
        ::core::ptr::read_volatile(self.register.get())
    }
}

/// A write-only register of type T.
///
/// Contains one value of type T and provides a volatile write function to it.
///
/// # Safety
/// This register should be used where writes to this peripheral register do not lead to memory
/// unsafety.
///
/// Access to this register must be synchronised; if multiple threads (or the main thread and an
/// interrupt service routine) are accessing it simultaneously you may encounter data races.
#[repr(transparent)]
pub struct WORegister<T> {
    register: UnsafeCell<T>,
}

impl<T: Copy> WORegister<T> {
    /// Writes a new value to the register.
    #[inline(always)]
    pub fn write(&self, val: T) {
        unsafe { ::core::ptr::write_volatile(self.register.get(), val) }
    }
}

/// A write-only register of type T, where write access is unsafe.
///
/// Contains one value of type T and provides a volatile write function to it.
///
/// # Safety
/// This register should be used where reads and writes to this peripheral may invoke
/// undefined behaviour or memory unsafety.
///
/// Access to this register must be synchronised; if multiple threads (or the main thread and an
/// interrupt service routine) are accessing it simultaneously you may encounter data races.
#[repr(transparent)]
pub struct UnsafeWORegister<T> {
    register: UnsafeCell<T>,
}

impl<T: Copy> UnsafeWORegister<T> {
    /// Writes a new value to the register.
    ///
    /// # Safety
    /// Refer to [UnsafeRWRegister]'s Safety section.
    #[inline(always)]
    pub unsafe fn write(&self, val: T) {
        ::core::ptr::write_volatile(self.register.get(), val)
    }
}

/// Write to a RWRegister or UnsafeRWRegister.
///
/// # Examples
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// // Safely acquire the peripheral instance (will panic if already acquired)
/// let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
///
/// // Write some value to the register.
/// write_reg!(stm32ral::gpio, gpioa, ODR, 1<<3);
///
/// // Write values to specific fields. Unspecified fields are written to 0.
/// write_reg!(stm32ral::gpio, gpioa, MODER, MODER3: Output, MODER4: Analog);
///
/// // Unsafe access without requiring you to first `take()` the instance
/// unsafe { write_reg!(stm32ral::gpio, GPIOA, MODER, MODER3: Output, MODER4: Analog) };
/// # }
/// ```
///
/// To support register arrays, each macro form also supports one or more array indices after the
/// register. For example, `write_reg!(stm32ral::gpio, gpioa, ODR[2], 42);` writes the value 42 to
/// the third register in an `ODR` register array.
///
/// # Usage
/// Like `modify_reg!`, this macro can be used in two ways, either with a single value to write to
/// the whole register, or with multiple fields each with their own value.
///
/// In both cases, the first arguments are:
/// * the path to the peripheral module: `stm32ral::gpio`,
/// * a reference to the instance of that peripheral: 'gpioa' (anything which dereferences to
///   `RegisterBlock`, such as `Instance`, `&Instance`, `&RegisterBlock`, or
///   `*const RegisterBlock`),
/// * the register (and offset, for arrays) you wish you access: `MODER` (a field on the
///   `RegisterBlock`).
///
/// In the single-value usage, the final argument is just the value to write:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// // Turn on PA3 (and turn everything else off).
/// write_reg!(stm32ral::gpio, gpioa, ODR, 1<<3);
/// # }
/// ```
///
/// Otherwise, the remaining arguments are each `Field: Value` pairs:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// // Set PA3 to Output, PA4 to Analog, and everything else to 0 (which is Input).
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// write_reg!(stm32ral::gpio, gpioa, MODER, MODER3: 0b01, MODER4: 0b11);
/// # }
/// ```
/// For fields with annotated values, you can also specify a named value:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// // As above, but with named values.
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// write_reg!(stm32ral::gpio, gpioa, MODER, MODER3: Output, MODER4: Analog);
/// # }
/// ```
///
/// This macro expands to calling `(*$instance).$register.write(value)`,
/// where in the second usage, the value is computed as the bitwise OR of
/// each field value, which are masked and shifted appropriately for the given field.
/// The named values are brought into scope by `use $peripheral::$register::$field::*` for
/// each field. The same constants could just be specified manually:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// // As above, but being explicit about named values.
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// write_reg!(stm32ral::gpio, gpioa, MODER, MODER3: stm32ral::gpio::MODER::MODER3::RW::Output,
///                                          MODER4: stm32ral::gpio::MODER::MODER4::RW::Analog);
/// # }
/// ```
///
/// The fully expanded form is equivalent to:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// // As above, but expanded.
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// (*gpioa).MODER.write(
///     ((stm32ral::gpio::MODER::MODER3::RW::Output << stm32ral::gpio::MODER::MODER3::offset)
///      & stm32ral::gpio::MODER::MODER3::mask)
///     |
///     ((stm32ral::gpio::MODER::MODER4::RW::Analog << stm32ral::gpio::MODER::MODER4::offset)
///      & stm32ral::gpio::MODER::MODER4::mask)
/// );
/// # }
/// ```
///
/// # Safety
/// This macro will require an unsafe function or block when used with an UnsafeRWRegister,
/// but not if used with RWRegister.
///
/// When run in an unsafe context, peripheral instances are directly accessible without requiring
/// having called `take()` beforehand:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// unsafe { write_reg!(stm32ral::gpio, GPIOA, MODER, MODER3: Output, MODER4: Analog) };
/// # }
/// ```
/// This works because `GPIOA` is a `*const RegisterBlock` in the `stm32ral::gpio` module;
/// and the macro brings such constants into scope and then dereferences the provided reference.
#[macro_export]
macro_rules! write_reg {
    ( $periph:path, $instance:expr, $reg:ident $([$offset:expr])*, $( $field:ident : $value:expr ),+ $(,)? ) => {{
        #[allow(unused_imports)]
        use $periph::{*};
        #[allow(unused_imports)]
        (*$instance).$reg $([$offset])*.write(
            $({
                use $periph::{$reg::$field::{W::*, RW::*}};
                ($value << { use $periph::{$reg::$field::offset}; offset })
                    & { use $periph::{$reg::$field::mask}; mask }
            }) | *
        );
    }};
    ( $periph:path, $instance:expr, $reg:ident $([$offset:expr])*, $value:expr ) => {{
        #[allow(unused_imports)]
        use $periph::{*};
        (*$instance).$reg $([$offset])*.write($value);
    }};
}

/// Modify a RWRegister or UnsafeRWRegister.
///
/// # Examples
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// // Safely acquire the peripheral instance (will panic if already acquired)
/// let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
///
/// // Update the register to ensure bit 3 is set.
/// modify_reg!(stm32ral::gpio, gpioa, ODR, |reg| reg | (1<<3));
///
/// // Write values to specific fields. Unspecified fields are left unchanged.
/// modify_reg!(stm32ral::gpio, gpioa, MODER, MODER3: Output, MODER4: Analog);
///
/// // Unsafe access without requiring you to first `take()` the instance
/// unsafe { modify_reg!(stm32ral::gpio, GPIOA, MODER, MODER3: Output, MODER4: Analog) };
/// # }
/// ```
///
/// To support register arrays, each macro form also supports one or more array indices after the
/// register. For example, `modify_reg!(stm32ral::gpio, gpioa, ODR[2], |reg| reg | (1<<3));` sets
/// a high bit in the third register of an `ODR` register array.
///
/// # Usage
/// Like `write_reg!`, this macro can be used in two ways, either with a modification of the entire
/// register, or by specifying which fields to change and what value to change them to.
///
/// In both cases, the first arguments are:
/// * the path to the peripheral module: `stm32ral::gpio`,
/// * a reference to the instance of that peripheral: 'gpioa' (anything which dereferences to
///   `RegisterBlock`, such as `Instance`, `&Instance`, `&RegisterBlock`, or
///   `*const RegisterBlock`),
/// * the register (and offset, for arrays) you wish you access: `MODER` (a field on the
///   `RegisterBlock`).
///
/// In the whole-register usage, the final argument is a closure that accepts the current value
/// of the register and returns the new value to write:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// // Turn on PA3 without affecting anything else.
/// modify_reg!(stm32ral::gpio, gpioa, ODR, |reg| reg | (1<<3));
/// # }
/// ```
///
/// Otherwise, the remaining arguments are `Field: Value` pairs:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// // Set PA3 to Output, PA4 to Analog, and leave everything else unchanged.
/// modify_reg!(stm32ral::gpio, gpioa, MODER, MODER3: 0b01, MODER4: 0b11);
/// # }
/// ```
///
/// For fields with annotated values, you can also specify a named value:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// // As above, but with named values.
/// modify_reg!(stm32ral::gpio, gpioa, MODER, MODER3: Output, MODER4: Analog);
/// # }
/// ```
///
/// This macro expands to calling `(*instance).register.write(value)`.
/// When called with a closure, `(*instance).register.read()` is called, the result
/// passed in to the closure, and the return value of the closure is used for `value`.
/// When called with `Field: Value` arguments, the current value is read and then masked
/// according to the specified fields, and then ORd with the OR of each field value,
/// each masked and shifted appropriately for the field. The named values are brought into scope
/// by `use peripheral::register::field::*` for each field. The same constants could just be
/// specified manually:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// // As above, but being explicit about named values.
/// modify_reg!(stm32ral::gpio, gpioa, MODER, MODER3: stm32ral::gpio::MODER::MODER3::RW::Output,
///                                           MODER4: stm32ral::gpio::MODER::MODER4::RW::Analog);
/// # }
/// ```
///
/// The fully expanded form is equivalent to:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// // As above, but expanded.
/// (*gpioa).MODER.write(
///     (
///         // First read the current value...
///         (*gpioa).MODER.read()
///         // Then AND it with an appropriate mask...
///         &
///         !( stm32ral::gpio::MODER::MODER3::mask | stm32ral::gpio::MODER::MODER4::mask )
///     )
///     // Then OR with each field value.
///     |
///         ((stm32ral::gpio::MODER::MODER3::RW::Output << stm32ral::gpio::MODER::MODER3::offset)
///          & stm32ral::gpio::MODER::MODER3::mask)
///     |
///         ((stm32ral::gpio::MODER::MODER4::RW::Analog << stm32ral::gpio::MODER::MODER3::offset)
///          & stm32ral::gpio::MODER::MODER3::mask)
/// );
/// # }
/// ```
///
/// # Safety
/// This macro will require an unsafe function or block when used with an UnsafeRWRegister,
/// but not if used with RWRegister.
///
/// When run in an unsafe context, peripheral instances are directly accessible without requiring
/// having called `take()` beforehand:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// unsafe { modify_reg!(stm32ral::gpio, GPIOA, MODER, MODER3: Output, MODER4: Analog) };
/// # }
/// ```
/// This works because `GPIOA` is a `*const RegisterBlock` in the `stm32ral::gpio` module;
/// and the macro brings such constants into scope and then dereferences the provided reference.
#[macro_export]
macro_rules! modify_reg {
    ( $periph:path, $instance:expr, $reg:ident $([$offset:expr])*, $( $field:ident : $value:expr ),+ $(,)? ) => {{
        #[allow(unused_imports)]
        use $periph::{*};
        #[allow(unused_imports)]
        (*$instance).$reg $([$offset])*.write(
            ((*$instance).$reg $([$offset])*.read() & !( $({ use $periph::{$reg::$field::mask}; mask }) | * ))
            | $({
                use $periph::{$reg::$field::{W::*, RW::*}};
                ($value << { use $periph::{$reg::$field::offset}; offset })
                    & { use $periph::{$reg::$field::mask}; mask }
            }) | *
        );
    }};
    ( $periph:path, $instance:expr, $reg:ident $([$offset:expr])*, $fn:expr ) => {{
        #[allow(unused_imports)]
        use $periph::{*};
        (*$instance).$reg $([$offset])*.write($fn((*$instance).$reg $([$offset])*.read()));
    }};
}

/// Read the value from a RORegister, RWRegister, UnsafeRORegister, or UnsafeRWRegister.
///
/// # Examples
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// // Safely acquire the peripheral instance (will panic if already acquired)
/// let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
///
/// // Read the whole register.
/// let val = read_reg!(stm32ral::gpio, gpioa, IDR);
///
/// // Read one field from the register.
/// let val = read_reg!(stm32ral::gpio, gpioa, IDR, IDR2);
///
/// // Read multiple fields from the register.
/// let (val1, val2, val3) = read_reg!(stm32ral::gpio, gpioa, IDR, IDR0, IDR1, IDR2);
///
/// // Check if one field is equal to a specific value, with the field's named values in scope.
/// while read_reg!(stm32ral::gpio, gpioa, IDR, IDR2 == High) {}
///
/// // Unsafe access without requiring you to first `take()` the instance
/// let val = unsafe { read_reg!(stm32ral::gpio, GPIOA, IDR) };
/// # }
/// ```
///
/// To support register arrays, each macro form also supports one or more array indices after the
/// register. For example, `read_reg!(stm32ral::gpio, gpioa, ODR[2]);` reads from the third
/// register of an `ODR` register array.
///
/// # Usage
/// Like `write_reg!`, this macro can be used multiple ways, either reading the entire register or
/// reading a one or more fields from it and potentially performing a comparison with one field.
///
/// In all cases, the first arguments are:
/// * the path to the peripheral module: `stm32ral::gpio`,
/// * a reference to the instance of that peripheral: 'gpioa' (anything which dereferences to
///   `RegisterBlock`, such as `Instance`, `&Instance`, `&RegisterBlock`, or
///   `*const RegisterBlock`),
/// * the register (and offset, for arrays) you wish to access: `IDR` (a field on the
///   `RegisterBlock`).
///
/// In the whole-register usage, the macro simply returns the register's value:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// // Read the entire value of GPIOA.IDR into `val`.
/// let val = read_reg!(stm32ral::gpio, gpioa, IDR);
/// # }
/// ```
///
/// For reading individual fields, the macro masks and shifts appropriately:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// // Read just the value of the field GPIOA.IDR2 into `val`.
/// let val = read_reg!(stm32ral::gpio, gpioa, IDR, IDR2);
///
/// // As above, but expanded for exposition:
/// let val = ((*gpioa).IDR.read() & stm32ral::gpio::IDR::IDR2::mask)
///           >> stm32ral::gpio::IDR::IDR2::offset;
///
/// // Read multiple fields
/// let (val1, val2) = read_reg!(stm32ral::gpio, gpioa, IDR, IDR2, IDR3);
///
/// // As above, but expanded for exposition:
/// let (val1, val2) = { let val = (*gpioa).IDR.read();
///     ((val & stm32ral::gpio::IDR::IDR2::mask) >> stm32ral::gpio::IDR::IDR2::offset,
///      (val & stm32ral::gpio::IDR::IDR3::mask) >> stm32ral::gpio::IDR::IDR3::offset,
///     )};
/// # }
/// ```
///
/// For comparing a single field, the macro masks and shifts and then performs the comparison:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// # let rcc = stm32ral::rcc::RCC::take().unwrap();
/// // Loop while PA2 is High.
/// while read_reg!(stm32ral::gpio, gpioa, IDR, IDR2 == High) {}
///
/// // Only proceed if the clock is not the HSI.
/// if read_reg!(stm32ral::rcc, rcc, CFGR, SWS != HSI) { }
///
/// // Equivalent expansion:
/// if (((*rcc).CFGR.read() & stm32ral::rcc::CFGR::SWS::mask)
///     >> stm32ral::rcc::CFGR::SWS::offset) != stm32ral::rcc::CFGR::SWS::R::HSI { }
/// # }
/// ```
///
/// # Safety
/// This macro will require an unsafe function or block when used with an UnsafeRWRegister or
/// UnsafeRORegister, but not if used with RWRegister, or RORegister.
///
/// When run in an unsafe context, peripheral instances are directly accessible without requiring
/// having called `take()` beforehand:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// let val = unsafe { read_reg!(stm32ral::gpio, GPIOA, MODER) };
/// # }
/// ```
/// This works because `GPIOA` is a `*const RegisterBlock` in the `stm32ral::gpio` module;
/// and the macro brings such constants into scope and then dereferences the provided reference.
#[macro_export]
macro_rules! read_reg {
    ( $periph:path, $instance:expr, $reg:ident $([$offset:expr])*, $( $field:ident ),+ $(,)? ) => {{
        #[allow(unused_imports)]
        use $periph::{*};
        let val = ((*$instance).$reg $([$offset])*.read());
        ( $({
            #[allow(unused_imports)]
            use $periph::{$reg::$field::{mask, offset, R::*, RW::*}};
            (val & mask) >> offset
        }) , *)
    }};
    ( $periph:path, $instance:expr, $reg:ident $([$offset:expr])*, $field:ident $($cmp:tt)* ) => {{
        #[allow(unused_imports)]
        use $periph::{*};
        #[allow(unused_imports)]
        use $periph::{$reg::$field::{mask, offset, R::*, RW::*}};
        (((*$instance).$reg $([$offset])*.read() & mask) >> offset) $($cmp)*
    }};
    ( $periph:path, $instance:expr, $reg:ident $([$offset:expr])* ) => {{
        #[allow(unused_imports)]
        use $periph::{*};
        ((*$instance).$reg $([$offset])*.read())
    }};
}

/// Reset a RWRegister, UnsafeRWRegister, WORegister, or UnsafeWORegister to its reset value.
///
/// # Examples
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// // Safely acquire the peripheral instance (will panic if already acquired)
/// let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
///
/// // Reset PA14 and PA15 to their reset state
/// reset_reg!(stm32ral::gpio, gpioa, GPIOA, MODER, MODER14, MODER15);
///
/// // Reset the entire GPIOA.MODER to its reset state
/// reset_reg!(stm32ral::gpio, gpioa, GPIOA, MODER);
/// # }
/// ```
///
/// To support register arrays, each macro form also supports one or more array indices after
/// the register. For example, `reset_reg!(stm32ral::gpio, gpioa, GPIOA, ODR[2]);` resets the
/// third register in an `ODR` register array.
///
/// # Usage
/// Like `write_reg!`, this macro can be used in two ways, either resetting the entire register
/// or just resetting specific fields within in. The register or fields are written with their
/// reset values.
///
/// In both cases, the first arguments are:
/// * the path to the peripheral module: `stm32ral::gpio`,
/// * a reference to the instance of that peripheral: 'gpioa' (anything which dereferences to
///   `RegisterBlock`, such as `Instance`, `&Instance`, `&RegisterBlock`, or
///   `*const RegisterBlock`),
/// * the module for the instance of that peripheral: `GPIOA`,
/// * the register (and offset, for arrays) you wish to access: `MODER` (a field on the
///   `RegisterBlock`).
///
/// In the whole-register usage, that's it:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// // Reset the entire GPIOA.MODER
/// reset_reg!(stm32ral::gpio, gpioa, GPIOA, MODER);
/// # }
/// ```
///
/// Otherwise, the remaining arguments are each field names:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// # let gpioa = stm32ral::gpio::GPIOA::take().unwrap();
/// // Reset the JTAG pins
/// reset_reg!(stm32ral::gpio, gpioa, GPIOA, MODER, MODER13, MODER14, MODER15);
/// reset_reg!(stm32ral::gpio, gpioa, GPIOB, MODER, MODER3, MODER4);
/// # }
/// ```
///
/// The second form is only available to RWRegister and UnsafeRWRegister, since `.read()` is
/// not available for WORegister and UnsafeWORegister.
///
/// This macro expands to calling `(*$instance).$register.write(value)`, where
/// `value` is either the register's reset value, or the current read value of the register
/// masked appropriately and combined with the reset value for each field.
///
/// # Safety
/// This macro will require an unsafe function or block when used with an UnsafeRWRegister or
/// UnsafeRORegister, but not if used with RWRegister or RORegister.
///
/// When run in an unsafe context, peripheral instances are directly accessible without requiring
/// having called `take()` beforehand:
/// ```rust,no_run
/// # use stm32ral::{read_reg, write_reg, modify_reg, reset_reg}; fn main() {
/// unsafe { reset_reg!(stm32ral::gpio, GPIOA, GPIOA, MODER) };
/// # }
/// ```
/// This works because `GPIOA` is a `*const RegisterBlock` in the `stm32ral::gpio` module;
/// and the macro brings such constants into scope and then dereferences the provided reference.
///
/// Note that the second argument is a `*const` and the third is a path; despite both being written
/// `GPIOA` they are not the same thing.
#[macro_export]
macro_rules! reset_reg {
    ( $periph:path, $instance:expr, $instancemod:path, $reg:ident $([$offset:expr])*, $( $field:ident ),+ $(,)? ) => {{
        #[allow(unused_imports)]
        use $periph::{*};
        use $periph::{$instancemod::{reset}};
        #[allow(unused_imports)]
        (*$instance).$reg $([$offset])*.write({
            let resetmask: u32 = $({ use $periph::{$reg::$field::mask}; mask }) | *;
            ((*$instance).$reg $([$offset])*.read() & !resetmask) | (reset.$reg & resetmask)
        });
    }};
    ( $periph:path, $instance:expr, $instancemod:path, $reg:ident $([$offset:expr])*) => {{
        #[allow(unused_imports)]
        use $periph::{*};
        use $periph::{$instancemod::{reset}};
        (*$instance).$reg $([$offset])*.write(reset.$reg);
    }};
}