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
use std::collections::HashMap;
use std::fmt::Write;

use crate::svd::Peripheral;
use proc_macro2::{Span, TokenStream};
use quote::quote;

use crate::util::{self, ident};
use crate::{Config, Target};
use anyhow::Result;

/// Generates code for `src/interrupt.rs`
pub fn render(
    target: Target,
    peripherals: &[Peripheral],
    device_x: &mut String,
    config: &Config,
) -> Result<TokenStream> {
    let interrupts = peripherals
        .iter()
        .flat_map(|p| {
            p.interrupt.iter().map(move |i| {
                (i, p.group_name.clone(), {
                    match p {
                        Peripheral::Single(info) => info.name.clone(),
                        Peripheral::Array(info, dim_element) => {
                            svd_rs::array::names(info, dim_element).next().unwrap()
                        }
                    }
                })
            })
        })
        .map(|i| (i.0.value, (i.0, i.1, i.2)))
        .collect::<HashMap<_, _>>();

    let mut interrupts = interrupts.into_values().collect::<Vec<_>>();
    interrupts.sort_by_key(|i| i.0.value);

    let mut root = TokenStream::new();
    let mut from_arms = TokenStream::new();
    let mut elements = TokenStream::new();
    let mut names = vec![];
    let mut names_cfg_attr = vec![];
    let mut variants = TokenStream::new();

    // Current position in the vector table
    let mut pos = 0;
    let mut mod_items = TokenStream::new();
    let span = Span::call_site();
    let feature_format = config.ident_formats.get("peripheral_feature").unwrap();
    for interrupt in &interrupts {
        while pos < interrupt.0.value {
            elements.extend(quote!(Vector { _reserved: 0 },));
            pos += 1;
        }
        pos += 1;

        let i_ty = ident(&interrupt.0.name, config, "interrupt", span);
        let description = format!(
            "{} - {}",
            interrupt.0.value,
            interrupt
                .0
                .description
                .as_ref()
                .map(|s| util::respace(s))
                .as_ref()
                .map(|s| util::escape_special_chars(s))
                .unwrap_or_else(|| interrupt.0.name.clone())
        );

        let value = util::unsuffixed(interrupt.0.value);

        let mut feature_attribute_flag = false;
        let mut feature_attribute = TokenStream::new();
        let mut not_feature_attribute = TokenStream::new();
        if config.feature_group && interrupt.1.is_some() {
            let feature_name = feature_format.apply(interrupt.1.as_ref().unwrap());
            feature_attribute_flag = true;
            feature_attribute.extend(quote! { #[cfg(feature = #feature_name)] });
            not_feature_attribute.extend(quote! { feature = #feature_name, });
        }
        if config.feature_peripheral {
            let feature_name = feature_format.apply(&interrupt.2);
            feature_attribute_flag = true;
            feature_attribute.extend(quote! { #[cfg(feature = #feature_name)] });
            not_feature_attribute.extend(quote! { feature = #feature_name, });
        }
        let not_feature_attribute = quote! { #[cfg(not(all(#not_feature_attribute)))] };

        variants.extend(quote! {
            #[doc = #description]
            #feature_attribute
            #i_ty = #value,
        });

        from_arms.extend(quote! {
            #feature_attribute
            #value => Ok(Interrupt::#i_ty),
        });

        if feature_attribute_flag {
            elements.extend(quote! {
                #not_feature_attribute
                Vector { _reserved: 0 },
                #feature_attribute
                Vector { _handler: #i_ty },
            });
        } else {
            elements.extend(quote!(Vector { _handler: #i_ty },));
        }
        names.push(i_ty);
        names_cfg_attr.push(feature_attribute);
    }

    let n = util::unsuffixed(pos);
    match target {
        Target::CortexM => {
            for name in &names {
                writeln!(device_x, "PROVIDE({name} = DefaultHandler);")?;
            }

            let link_section_name = config
                .interrupt_link_section
                .as_deref()
                .unwrap_or(".vector_table.interrupts");
            let link_section_attr = quote! {
                #[link_section = #link_section_name]
            };

            root.extend(quote! {
                #[cfg(feature = "rt")]
                extern "C" {
                    #(#names_cfg_attr fn #names();)*
                }

                #[doc(hidden)]
                #[repr(C)]
                pub union Vector {
                    _handler: unsafe extern "C" fn(),
                    _reserved: u32,
                }

                #[cfg(feature = "rt")]
                #[doc(hidden)]
                #link_section_attr
                #[no_mangle]
                pub static __INTERRUPTS: [Vector; #n] = [
                    #elements
                ];
            });
        }
        Target::Msp430 => {
            for name in &names {
                writeln!(device_x, "PROVIDE({name} = DefaultHandler);").unwrap();
            }

            let link_section_name = config
                .interrupt_link_section
                .as_deref()
                .unwrap_or(".vector_table.interrupts");
            let link_section_attr = quote! {
                #[link_section = #link_section_name]
            };

            root.extend(quote! {
                #[cfg(feature = "rt")]
                extern "msp430-interrupt" {
                    #(#names_cfg_attr fn #names();)*
                }

                #[doc(hidden)]
                #[repr(C)]
                pub union Vector {
                    _handler: unsafe extern "msp430-interrupt" fn(),
                    _reserved: u16,
                }

                #[cfg(feature = "rt")]
                #[doc(hidden)]
                #link_section_attr
                #[no_mangle]
                #[used]
                pub static __INTERRUPTS:
                    [Vector; #n] = [
                        #elements
                    ];
            });
        }
        Target::RISCV => {
            for name in &names {
                writeln!(device_x, "PROVIDE({name} = DefaultHandler);")?;
            }

            let link_section_attr = config.interrupt_link_section.as_ref().map(|section| {
                quote! {
                    #[link_section = #section]
                }
            });

            root.extend(quote! {
                #[cfg(feature = "rt")]
                extern "C" {
                    #(#names_cfg_attr fn #names();)*
                }

                #[doc(hidden)]
                #[repr(C)]
                pub union Vector {
                    pub _handler: unsafe extern "C" fn(),
                    pub _reserved: usize,
                }

                #[cfg(feature = "rt")]
                #[doc(hidden)]
                #link_section_attr
                #[no_mangle]
                pub static __EXTERNAL_INTERRUPTS: [Vector; #n] = [
                    #elements
                ];
            });
        }
        Target::XtensaLX => {
            for name in &names {
                writeln!(device_x, "PROVIDE({name} = DefaultHandler);")?;
            }

            let link_section_attr = config.interrupt_link_section.as_ref().map(|section| {
                quote! {
                    #[link_section = #section]
                }
            });

            root.extend(quote! {
                #[cfg(feature = "rt")]
                extern "C" {
                    #(#names_cfg_attr fn #names();)*
                }

                #[doc(hidden)]
                #[repr(C)]
                pub union Vector {
                    pub _handler: unsafe extern "C" fn(),
                    _reserved: u32,
                }

                #[cfg(feature = "rt")]
                #link_section_attr
                #[doc(hidden)]
                pub static __INTERRUPTS: [Vector; #n] = [
                    #elements
                ];
            });
        }
        Target::Mips => {}
        Target::None => {}
    }

    let self_token = quote!(self);
    let (enum_repr, nr_expr) = if variants.is_empty() {
        (quote!(), quote!(match #self_token {}))
    } else {
        (quote!(#[repr(u16)]), quote!(#self_token as u16))
    };

    let defmt = config
        .impl_defmt
        .as_ref()
        .map(|feature| quote!(#[cfg_attr(feature = #feature, derive(defmt::Format))]));

    if target == Target::Msp430 {
        let interrupt_enum = quote! {
            ///Enumeration of all the interrupts. This enum is seldom used in application or library crates. It is present primarily for documenting the device's implemented interrupts.
            #defmt
            #[derive(Copy, Clone, Debug, PartialEq, Eq)]
            #enum_repr
            pub enum Interrupt {
                #variants
            }
        };

        root.extend(interrupt_enum);
    } else {
        let interrupt_enum = quote! {
            ///Enumeration of all the interrupts.
            #defmt
            #[derive(Copy, Clone, Debug, PartialEq, Eq)]
            #enum_repr
            pub enum Interrupt {
                #variants
            }
        };

        match target {
            Target::CortexM => {
                root.extend(quote! {
                    #interrupt_enum

                    unsafe impl cortex_m::interrupt::InterruptNumber for Interrupt {
                        #[inline(always)]
                        fn number(#self_token) -> u16 {
                            #nr_expr
                        }
                    }
                });
            }
            Target::XtensaLX => {
                root.extend(quote! {
                    #interrupt_enum

                    unsafe impl xtensa_lx::interrupt::InterruptNumber for Interrupt {
                        #[inline(always)]
                        fn number(#self_token) -> u16 {
                            #nr_expr
                        }
                    }

                    /// TryFromInterruptError
                    #[derive(Debug, Copy, Clone)]
                    pub struct TryFromInterruptError(());

                    impl Interrupt {

                        /// Attempt to convert a given value into an `Interrupt`
                        #[inline]
                        pub fn try_from(value: u16) -> Result<Self, TryFromInterruptError> {
                            match value {
                                #from_arms
                                _ => Err(TryFromInterruptError(())),
                            }
                        }
                    }
                });
            }
            _ => {
                mod_items.extend(quote! {
                    #interrupt_enum

                    /// TryFromInterruptError
                    #[derive(Debug, Copy, Clone)]
                    pub struct TryFromInterruptError(());

                    impl Interrupt {

                        /// Attempt to convert a given value into an `Interrupt`
                        #[inline]
                        pub fn try_from(value: u8) -> Result<Self, TryFromInterruptError> {
                            match value {
                                #from_arms
                                _ => Err(TryFromInterruptError(())),
                            }
                        }
                    }
                });
            }
        }
    }

    if target != Target::None {
        let abi = match target {
            Target::Msp430 => "msp430-interrupt",
            _ => "C",
        };

        if target != Target::CortexM
            && target != Target::Msp430
            && target != Target::XtensaLX
            && target != Target::Mips
        {
            mod_items.extend(quote! {
                #[cfg(feature = "rt")]
                #[macro_export]
                /// Assigns a handler to an interrupt
                ///
                /// This macro takes two arguments: the name of an interrupt and the path to the
                /// function that will be used as the handler of that interrupt. That function
                /// must have signature `fn()`.
                ///
                /// Optionally, a third argument may be used to declare interrupt local data.
                /// The handler will have exclusive access to these *local* variables on each
                /// invocation. If the third argument is used then the signature of the handler
                /// function must be `fn(&mut $NAME::Locals)` where `$NAME` is the first argument
                /// passed to the macro.
                ///
                /// # Example
                ///
                /// ``` ignore
                /// interrupt!(TIM2, periodic);
                ///
                /// fn periodic() {
                ///     print!(".");
                /// }
                ///
                /// interrupt!(TIM3, tick, locals: {
                ///     tick: bool = false;
                /// });
                ///
                /// fn tick(locals: &mut TIM3::Locals) {
                ///     locals.tick = !locals.tick;
                ///
                ///     if locals.tick {
                ///         println!("Tick");
                ///     } else {
                ///         println!("Tock");
                ///     }
                /// }
                /// ```
                macro_rules! interrupt {
                    ($NAME:ident, $path:path, locals: {
                        $($lvar:ident:$lty:ty = $lval:expr;)*
                    }) => {
                        #[allow(non_snake_case)]
                        mod $NAME {
                            pub struct Locals {
                                $(
                                    pub $lvar: $lty,
                                )*
                            }
                        }

                        #[allow(non_snake_case)]
                        #[no_mangle]
                        pub extern #abi fn $NAME() {
                            // check that the handler exists
                            let _ = $crate::interrupt::Interrupt::$NAME;

                            static mut LOCALS: self::$NAME::Locals =
                                self::$NAME::Locals {
                                    $(
                                        $lvar: $lval,
                                    )*
                                };

                            // type checking
                            let f: fn(&mut self::$NAME::Locals) = $path;
                            f(unsafe { &mut LOCALS });
                        }
                    };
                    ($NAME:ident, $path:path) => {
                        #[allow(non_snake_case)]
                        #[no_mangle]
                        pub extern #abi fn $NAME() {
                            // check that the handler exists
                            let _ = $crate::interrupt::Interrupt::$NAME;

                            // type checking
                            let f: fn() = $path;
                            f();
                        }
                    }
                }
            });
        }
    }

    if !interrupts.is_empty()
        && target != Target::CortexM
        && target != Target::XtensaLX
        && target != Target::Msp430
    {
        root.extend(quote! {
            #[doc(hidden)]
            pub mod interrupt {
                #mod_items
            }
        });

        root.extend(quote! {
            pub use self::interrupt::Interrupt;
        });
    }

    Ok(root)
}