Skip to main content

rrkernel_macros/
lib.rs

1//! Attribute macros for rrkernel.
2//!
3//! One macro, [`macro@rrkernel`], and everything it removes from an application: the
4//! kernel configuration call site, the "main is task 0" plumbing, the exit path, the
5//! vector-table wiring, the fault handlers and the panic handler.
6
7use proc_macro::TokenStream;
8use quote::quote;
9use syn::{parse_macro_input, ItemFn};
10
11/// Turn a `cortex-m-rt` `main` into the kernel's **task 0**.
12///
13/// ```ignore
14/// #![no_std]
15/// #![no_main]
16///
17/// use rrkernel::{scheduler, thread, Slice};
18///
19/// const CORE_HZ: u32 = 8_000_000;
20///
21/// #[rrkernel]
22/// #[cortex_m_rt::entry]           // keep the ecosystem's entry point
23/// fn main() -> ! {
24///     // optional, one line: where a panic or a fault should be reported
25///     rrkernel::log_with(|a| { /* e.g. rtt_target::rprintln!("{}", a) */ });
26///
27///     // the kernel, configured once. No `Result` to ignore: it either starts or says
28///     // why through the log above and then parks.
29///     rrkernel::configure(CORE_HZ, Slice::Millis(1), 1024);
30///
31///     thread::spawn(worker);
32///     loop { scheduler::sleep_ticks(1000); }
33/// }
34///
35/// fn worker() { /* ... */ }
36/// ```
37///
38/// What it expands to:
39///
40/// * the function itself, with its attributes preserved, its signature forced to `-> !`
41///   (the body is followed by the exit path, so it cannot return);
42/// * `rrkernel::app_support::exit_main()` after the body: `main` *is* task 0, so returning
43///   unlinks it and switches away for good, exactly like any other task;
44/// * a strong `HardFault`, a strong `DefaultHandler` and a `#[panic_handler]` that report
45///   through the `log_with` sink before parking — so a fault can never look like a hang,
46///   and the application needs no `panic-halt`.
47///
48/// Apply it once per program, above `#[cortex_m_rt::entry]`.
49#[proc_macro_attribute]
50pub fn rrkernel(attr: TokenStream, item: TokenStream) -> TokenStream {
51    let mut func = parse_macro_input!(item as ItemFn);
52
53    // The generated body ends with `exit_main()`, so the signature must not return. This
54    // is also why the application does not have to write `-> !` itself.
55    func.sig.output = syn::parse_quote!(-> !);
56
57    // Re-emit only what belongs to an entry point: its attributes (notably
58    // `#[cortex_m_rt::entry]`, which must survive for the vector table), visibility and
59    // name. Parameters and generics are dropped; an entry point has none.
60    let attrs = func.attrs.clone();
61    let vis = func.vis.clone();
62    let name = func.sig.ident.clone();
63    let body = func.block.clone();
64
65    // `#[rrkernel(log = rtt)]` wires RTT — terminal, guard and sink — so an application
66    // writes none of that boilerplate. Anything else, including no argument at all, leaves
67    // the kernel's built-in RAM buffer as the sink, which needs no setup whatsoever.
68    let log_setup = match log_choice(attr).as_deref() {
69        Some("rtt") => quote! {
70            // RTT over the debug probe. The terminal is initialized here, and the flag
71            // keeps the sink from being called before it exists.
72            static RTT_UP: core::sync::atomic::AtomicBool =
73                core::sync::atomic::AtomicBool::new(false);
74            rtt_target::rtt_init_print!();
75            RTT_UP.store(true, core::sync::atomic::Ordering::Relaxed);
76            rrkernel::log_with(|a| {
77                if RTT_UP.load(core::sync::atomic::Ordering::Relaxed) {
78                    let _ = rtt_target::rprintln!("{}", a);
79                }
80            });
81        },
82        _ => quote! {},
83    };
84
85    quote! {
86        #(#attrs)*
87        #vis fn #name() -> ! {
88            #log_setup
89            // Mask interrupts once at startup, and (not incidentally) reference the
90            // `cortex-m` crate: its `critical-section` implementation is what `rtt-target`
91            // and most of the ecosystem link against, and a crate that nothing references
92            // is a crate the linker never pulls in. Without this the link fails with
93            // `undefined symbol: _critical_section_1_0_acquire`, which says nothing about
94            // the real cause. A cast of the item is not enough — it is generic, so it needs
95            // annotations — hence the call.
96            let _ = cortex_m::interrupt::free(|_cs| ());
97            #body
98            // `main` IS task 0: its body has run to completion, so unlink it and switch
99            // away for good — exactly like any other task that returns.
100            rrkernel::app_support::exit_main()
101        }
102
103        #[no_mangle]
104        pub extern "C" fn HardFault() -> ! {
105            rrkernel::app_support::hard_fault()
106        }
107
108        #[no_mangle]
109        pub extern "C" fn DefaultHandler() -> ! {
110            rrkernel::app_support::unexpected_exception()
111        }
112
113        #[panic_handler]
114        fn __rrkernel_panic(info: &core::panic::PanicInfo) -> ! {
115            rrkernel::app_support::panic(info)
116        }
117    }
118    .into()
119}
120
121/// Read `log = <name>` out of the attribute arguments, e.g. `#[rrkernel(log = rtt)]`.
122///
123/// Kept deliberately small: the only recognised value today is `rtt`. Anything else — no
124/// argument, or an unknown word — means "use the kernel's built-in default sink", which
125/// needs no setup and never fails to compile.
126fn log_choice(attr: TokenStream) -> Option<String> {
127    if attr.is_empty() {
128        return None;
129    }
130    use syn::parse::Parser;
131    let metas = syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated
132        .parse(attr)
133        .ok()?;
134    for m in metas {
135        if let syn::Meta::NameValue(nv) = m {
136            if nv.path.is_ident("log") {
137                if let syn::Expr::Path(p) = nv.value {
138                    return p.path.get_ident().map(|i| i.to_string());
139                }
140            }
141        }
142    }
143    None
144}