rumio 0.2.0

Control your MMIO and CPU registers without pain.
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
/// Define abstractions for a single register inside an MMIO block.
///
/// The macro looks almost the same as [`define_cpu_register`](crate::define_cpu_register),
/// and all the field types and properties of the CPU register version apply here too.
///
/// **Note** that the generated struct for this register doesn't has the same layout
/// as the given number type, and should always be constructed using the `new` method.
///
/// # Example
///
/// ```
/// rumio::define_mmio_register! {
///     Reg: u16 {
///         rw MODE: 0..1 = enum Mode [
///             A = 0b00,
///             B = 0b01,
///             C = 0b10,
///             D = 0b11,
///         ],
///
///         r FOO: 2,
///
///         rw BAR: 3,
///         rw BAZ: 4,
///
///         rw FLAGS: 5..8 = flags Flags [
///             A = 0b0001,
///             B = 0b0010,
///             C = 0b0100,
///             D = 0b1000,
///         ],
///     }
/// }
/// ```
///
///
/// To explore the whole generated api, take a look at the
/// `example_generated` module on docs.rs
#[macro_export]
macro_rules! define_mmio_register {
    ($(#[$reg_attr:meta])*
     $reg_name:ident: $num_ty:ty { $(
     $(#[$field_attr:meta])*
     $perm:ident $name:ident: $from:literal $( .. $to:literal =
         $(#[$kind_attr:meta])*
         $kind_type:ident $kind_name:ident [
             $(
                 $(#[$kind_variant_attr:meta])*
                 $kind_variant:ident = $kind_variant_val:expr
             ),*$(,)?
         ]
     )?
    ),*$(,)?
    }) => {
        const _: fn() = || {
            fn assert_impl<T: $crate::Int>() {}
            assert_impl::<$num_ty>();
        };

        $($(
            $crate::__generate_field_kinds__!($num_ty, $perm, $from .. $to,
                $(#[$kind_attr])*
                $kind_type $kind_name [
                    $(
                        $(#[$kind_variant_attr])*
                        $kind_variant = $kind_variant_val
                    ),*
                ]
            );
        )*)?

        $(
            $(#[$field_attr])*
            #[derive(Clone, Copy, Debug, PartialEq, Eq)]
            #[allow(non_camel_case_types)]
            pub struct $name($crate::mmio::VolAddr<$num_ty>);
        )*

        $(#[$reg_attr])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        pub struct $reg_name($crate::mmio::VolAddr<$num_ty>);

        #[allow(dead_code)]
        impl $reg_name {
            /// Create a new instance of this register at the given address.
            #[inline]
            pub const fn new(addr: $crate::mmio::VolAddr<$num_ty>) -> Self {
                Self(addr)
            }

            $crate::__generate_if_perm__! { @read
                /// Get the raw value from this MMIO register.
                pub fn get(self) -> $num_ty {
                    $crate::mmio::VolAddr::<$num_ty>::read(self.0)
                }
                => $($perm) *
            }

            $crate::__generate_if_perm__! { @write
                /// Write the raw value into this MMIO register.
                pub fn set(self, val: $num_ty) {
                    $crate::mmio::VolAddr::<$num_ty>::write(self.0, val);
                }
                => $($perm) *
            }

            $crate::__generate_if_perm__! { @read
                /// Check if one of the given fields is set.
                ///
                /// Returns `true` if the value specified by the field is not null.
                pub fn is_set<P: $crate::perm::Permission>(self, field: $crate::Field<$num_ty, P>) -> ::core::primitive::bool {
                    let val = $crate::mmio::VolAddr::<$num_ty>::read(self.0);
                    $crate::Field::<$num_ty, P>::read(field, val) != 0
                }
                => $($perm) *
            }

            $crate::__generate_if_perm__! { @read
                /// Read the given field from this register.
                pub fn read<P: $crate::perm::Permission>(self, field: $crate::Field<$num_ty, P>) -> $num_ty {
                    let val = $crate::mmio::VolAddr::<$num_ty>::read(self.0);
                    $crate::Field::<$num_ty, P>::read(field, val)
                }
                => $($perm) *
            }

            $crate::__generate_if_perm__! { @write
                /// Write the given values into this register and set all other bits to 0.
                pub fn write(self, val: $crate::Value<$num_ty>) {
                    let val = $crate::Value::<$num_ty>::modify(val, 0);
                    $crate::mmio::VolAddr::<$num_ty>::write(self.0, val);
                }
                => $($perm) *
            }

            $crate::__generate_if_perm__! { @read_write
                /// Modify this register to match the given value, but keep all other bits untouched.
                pub fn modify(self, val: $crate::Value<$num_ty>) {
                    let reg = $crate::mmio::VolAddr::<$num_ty>::read(self.0);
                    let reg = $crate::Value::<$num_ty>::modify(val, reg);
                    $crate::mmio::VolAddr::<$num_ty>::write(self.0, reg);
                }
                => $($perm) *
            }

            $(#[allow(non_snake_case)]
            $(#[$field_attr])*
            pub fn $name(&self) -> $name {
                $name(self.0)
            })*
        }

        $(
            $crate::define_mmio_register!(@internal, $num_ty, $perm $name: $from $(.. $to =
                $kind_type $kind_name [
                    $($kind_variant = $kind_variant_val),*
                ]
            )?);
        )*
    };

    // =====================================
    // Read and write bitflags
    // =====================================

    (@internal, $num_ty:ty, rw $name:ident: $from:literal .. $to:literal = flags $kind_name:ident [
        $($kind_variant:ident = $kind_variant_val:expr),*
    ]) => {
        $crate::define_mmio_register!(@internal, $num_ty, r $name: $from .. $to = flags $kind_name [
            $($kind_variant = $kind_variant_val),*
        ]);

        $crate::define_mmio_register!(@internal, $num_ty, w $name: $from .. $to = flags $kind_name [
            $($kind_variant = $kind_variant_val),*
        ]);
    };

    (@internal, $num_ty:ty, r $name:ident: $from:literal .. $to:literal = flags $kind_name:ident [
        $($kind_variant:ident = $kind_variant_val:expr),*
    ]) => {
        impl $name {
            /// Read the raw bits from the register and return a struct representing
            /// all flags of this bit range.
            #[allow(unused)]
            pub fn get(&self) -> $kind_name {
                let val = $crate::mmio::VolAddr::<$num_ty>::read(self.0);
                $kind_name::from_bits_truncate($crate::get_bits(val, ($from, $to)))
            }
        }
    };

    (@internal, $num_ty:ty, w $name:ident: $from:literal .. $to:literal = flags $kind_name:ident [
        $($kind_variant:ident = $kind_variant_val:expr),*
    ]) => {
        impl $name {
            /// Set this bit range to the given bitflags.
            #[allow(unused)]
            pub fn set(&self, flags: $kind_name) {
                let bits = $kind_name::bits(&flags);
                let val = $crate::mmio::VolAddr::<$num_ty>::read(self.0);
                $crate::mmio::VolAddr::<$num_ty>::write(self.0, $crate::set_bits(val, ($from, $to), bits));
            }
        }
    };

    // =====================================
    // Read and write a enum range of bits
    // =====================================

    (@internal, $num_ty:ty, rw $name:ident: $from:literal .. $to:literal = enum $kind_name:ident [
        $($kind_variant:ident = $kind_variant_val:expr),*
    ]) => {
        $crate::define_mmio_register!(@internal, $num_ty, r $name: $from .. $to = enum $kind_name [
            $($kind_variant = $kind_variant_val),*
        ]);

        $crate::define_mmio_register!(@internal, $num_ty, w $name: $from .. $to = enum $kind_name [
            $($kind_variant = $kind_variant_val),*
        ]);
    };

    (@internal, $num_ty:ty, r $name:ident: $from:literal .. $to:literal = enum $kind_name:ident [
        $($kind_variant:ident = $kind_variant_val:expr),*
    ]) => {
        impl $name {
            /// Read the raw bits from the register, and then try to map them to an enum.
            #[allow(unused)]
            pub fn get(&self) -> ::core::option::Option<$kind_name> {
                let val = $crate::mmio::VolAddr::<$num_ty>::read(self.0);
                match $crate::get_bits(val, ($from, $to)) {
                    $($kind_variant_val => ::core::option::Option::Some($kind_name::$kind_variant),)*
                    _ => ::core::option::Option::None,
                }
            }
        }
    };

    (@internal, $num_ty:ty, w $name:ident: $from:literal .. $to:literal = enum $kind_name:ident [
        $($kind_variant:ident = $kind_variant_val:expr),*
    ]) => {
        impl $name {
            /// Set this bits to the given value.
            #[allow(unused)]
            pub fn set(&self, val: $kind_name) {
                let bits = match val {
                    $($kind_name::$kind_variant => $kind_variant_val,)*
                };
                let val = $crate::mmio::VolAddr::<$num_ty>::read(self.0);
                let val = $crate::set_bits(val, ($from, $to), bits);
                $crate::mmio::VolAddr::<$num_ty>::write(self.0, val);
            }
        }
    };

    // =====================================
    // Read and write a single bit
    // =====================================

    (@internal, $num_ty:ty, $perm:ident $name:ident: $bit:literal) => {
        impl $name {
            /// A `Field` that covers this single bit.
            #[allow(unused)]
            pub const FIELD: $crate::Field<$num_ty, $crate::__perm_for_name__!($perm)> = $crate::Field::<$num_ty, _>::new(1 << $bit);
        }

        $crate::define_mmio_register!(@internal_bit, $num_ty, $perm $name: $bit);
    };

    (@internal_bit, $num_ty:ty, rw $name:ident: $bit:literal) => {
        $crate::define_mmio_register!(@internal_bit, $num_ty, r $name: $bit);
        $crate::define_mmio_register!(@internal_bit, $num_ty, w $name: $bit);
    };

    (@internal_bit, $num_ty:ty, r $name:ident: $bit:literal) => {
        impl $name {
            /// Check if this bit is set inside the MMIO.
            #[allow(unused)]
            pub fn get(&self) -> ::core::primitive::bool {
                let val = $crate::mmio::VolAddr::<$num_ty>::read(self.0);
                val & (1 << $bit) != 0
            }
        }
    };

    (@internal_bit, $num_ty:ty, w $name:ident: $bit:literal) => {
        impl $name {
            /// A `Value` that will set this bit to high when modifying a register.
            #[allow(unused)]
            pub const SET: $crate::Value<$num_ty> = $crate::Value::<$num_ty>::new(1 << $bit, 1 << $bit);

            /// A `Value` that will set this bit to low when modifying a register.
            #[allow(unused)]
            pub const CLEAR: $crate::Value<$num_ty> = $crate::Value::<$num_ty>::new(1 << $bit, 0);

            /// Set the value of this bit inside the MMIO.
            #[allow(unused)]
            pub fn set(&self, x: ::core::primitive::bool) {
                const MASK: $num_ty = 1 << $bit;
                let val = $crate::mmio::VolAddr::<$num_ty>::read(self.0);
                let val = match x {
                    true => val | MASK,
                    false => val & !MASK,
                };
                $crate::mmio::VolAddr::<$num_ty>::write(self.0, val);
            }
        }
    };
}

/// Creates a struct which represents the MMIO block and all their registers.
///
/// **Note** that the generated struct **does not** has the same layout as
/// you provided in this macro. So it must not be created like this:
///
/// ```ignore
/// let registers = unsafe { &*(0x4000_8000 as *const MmioDevice) };
/// ```
///
/// You must use the `new` method that is generated.
///
/// # Example
///
/// ```
/// rumio::define_mmio_register! {
///     Reg: u16 {
///         rw MODE: 0..1 = enum Mode [
///             A = 0b00,
///             B = 0b01,
///             C = 0b10,
///             D = 0b11,
///         ],
///
///         r FOO: 2,
///
///         rw BAR: 3,
///         rw BAZ: 4,
///
///         rw FLAGS: 5..8 = flags Flags [
///             A = 0b0001,
///             B = 0b0010,
///             C = 0b0100,
///             D = 0b1000,
///         ],
///     }
/// }
///
/// rumio::define_mmio_struct! {
///     pub struct Device {
///         (0x00 => one: Reg),
///         (0x08 => two: Reg),
///     }
/// }
/// ```
///
///
/// To explore the whole generated api, take a look at the
/// `example_generated` module on docs.rs
#[macro_export]
macro_rules! define_mmio_struct {
    ($(#[$attr:meta])*
     $pub:vis struct $name:ident {$(
         $(#[$field_attr:meta])*
         ($field_offset:expr => $field_name:ident: $field_ty:ty)
    ),*$(,)?}) => { $crate::defile::item! {
        $(#[$attr])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        $pub struct $name($crate::mmio::VolAddr<u8>);

        impl $name {
            /// Create a new MMIO region at the given address.
            ///
            /// # Safety
            ///
            /// The safety arguments of `VolAddr` and
            /// it's `new` method must be guaranteed.
            #[allow(unused)]
            pub const unsafe fn new(addr: ::core::primitive::usize) -> Self {
                Self($crate::mmio::VolAddr::<u8>::new(addr))
            }

            $( $crate::define_mmio_struct!(@@create_field, $(#[$field_attr])*, $field_name, @$field_ty, $field_offset); )*
        }
    }};

    (@create_field, $(#[$attr:meta])*, $name:ident, [$T:ty; $N:expr], $off:expr) => {
        $(#[$attr])*
        #[allow(unused)]
        pub fn $name(&self, idx: usize) -> $T {
            <$T>::new(unsafe {
                $crate::mmio::VolAddr::cast(
                    $crate::mmio::VolAddr::offset(self.0, ($off + <$T>::size() * idx) as isize)
                )
            })
        }
    };

    (@create_field, $(#[$attr:meta])*, $name:ident, $T:ty, $off:expr) => {
        $(#[$attr])*
        #[allow(unused, non_snake_case)]
        pub fn $name(&self) -> $T {
            <$T>::new(unsafe {
                $crate::mmio::VolAddr::cast(
                    $crate::mmio::VolAddr::offset(self.0, $off)
                )
            })
        }
    };
}