cortex_m_rtic_macros/codegen/
post_init.rs

1use proc_macro2::{Span, TokenStream as TokenStream2};
2use quote::quote;
3use rtic_syntax::ast::App;
4use syn::Index;
5
6use crate::{analyze::Analysis, codegen::util};
7
8/// Generates code that runs after `#[init]` returns
9pub fn codegen(app: &App, analysis: &Analysis) -> Vec<TokenStream2> {
10    let mut stmts = vec![];
11
12    // Initialize shared resources
13    for (name, res) in &app.shared_resources {
14        let mangled_name = util::static_shared_resource_ident(name);
15        // If it's live
16        let cfgs = res.cfgs.clone();
17        if analysis.shared_resources.get(name).is_some() {
18            stmts.push(quote!(
19                // We include the cfgs
20                #(#cfgs)*
21                // Resource is a RacyCell<MaybeUninit<T>>
22                // - `get_mut` to obtain a raw pointer to `MaybeUninit<T>`
23                // - `write` the defined value for the late resource T
24                #mangled_name.get_mut().write(core::mem::MaybeUninit::new(shared_resources.#name));
25            ));
26        }
27    }
28
29    // Initialize local resources
30    for (name, res) in &app.local_resources {
31        let mangled_name = util::static_local_resource_ident(name);
32        // If it's live
33        let cfgs = res.cfgs.clone();
34        if analysis.local_resources.get(name).is_some() {
35            stmts.push(quote!(
36                // We include the cfgs
37                #(#cfgs)*
38                // Resource is a RacyCell<MaybeUninit<T>>
39                // - `get_mut` to obtain a raw pointer to `MaybeUninit<T>`
40                // - `write` the defined value for the late resource T
41                #mangled_name.get_mut().write(core::mem::MaybeUninit::new(local_resources.#name));
42            ));
43        }
44    }
45
46    for (i, (monotonic_ident, monotonic)) in app.monotonics.iter().enumerate() {
47        // For future use
48        // let doc = format!(" RTIC internal: {}:{}", file!(), line!());
49        // stmts.push(quote!(#[doc = #doc]));
50        let cfgs = &monotonic.cfgs;
51
52        #[allow(clippy::cast_possible_truncation)]
53        let idx = Index {
54            index: i as u32,
55            span: Span::call_site(),
56        };
57        stmts.push(quote!(
58            #(#cfgs)*
59            monotonics.#idx.reset();
60        ));
61
62        // Store the monotonic
63        let name = util::monotonic_ident(&monotonic_ident.to_string());
64        stmts.push(quote!(
65            #(#cfgs)*
66            #name.get_mut().write(Some(monotonics.#idx));
67        ));
68    }
69
70    // Enable the interrupts -- this completes the `init`-ialization phase
71    stmts.push(quote!(rtic::export::interrupt::enable();));
72
73    stmts
74}