Skip to main content

hopter_proc_macro/
lib.rs

1//! Procedual macro implementations for the [`#[main]`](main)
2//! and [`#[handler(IRQ)]`](handler) attribute macro.
3
4use proc_macro::TokenStream;
5use proc_macro2::TokenStream as TokenStream2;
6use quote::quote;
7use syn::{
8    parse_macro_input, AttributeArgs, ItemFn, Meta, NestedMeta, ReturnType, Signature, Type,
9};
10
11/// Mark a function as the entry function of the main task.
12///
13/// The function should satisfy the following signature requirements:
14/// - Has one and only one argument of type `cortex_m::Peripherals`.
15/// - Returns `()` or `!`.
16/// - Is not `async`.
17/// - Is not `unsafe`.
18/// - Is not variadic.
19///
20/// Example:
21/// ```rust
22/// #[main]
23/// fn main(cp: cortex_m::Peripherals) {
24///    /* initialize system */
25///    /* create other tasks */
26/// }
27/// ```
28///
29/// The macro works by generating a trampoline function to call the user
30/// defined main function. The macro expands to the following for the above
31/// example:
32///
33/// ```rust
34/// #[no_mangle]
35/// extern "Rust" fn __main_trampoline(arg: AtomicPtr<u8>) {
36///     let arg = arg.load(Ordering::SeqCst) as *mut cortex_m::Peripherals;
37///     let arg = unsafe { Box::from_raw(arg) };
38///     main(*arg)
39/// }
40/// ```
41#[proc_macro_attribute]
42pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
43    // Parse the `item` TokenStream into a Rust function.
44    let main_func = parse_macro_input!(item as ItemFn);
45
46    check_main_function_signature(&main_func.sig);
47
48    // Store the function's name.
49    let func_name = main_func.sig.ident.to_string();
50
51    // Generate the trampoline function string.
52    let trampoline = format!(
53        "\
54        #[no_mangle]\n\
55        extern \"Rust\" fn __main_trampoline(arg: core::sync::atomic::AtomicPtr<u8>) {{\n\
56            let arg = arg.load(core::sync::atomic::Ordering::SeqCst) as *mut cortex_m::Peripherals;\n\
57            let arg = unsafe {{ alloc::boxed::Box::from_raw(arg) }};\n\
58            {}(*arg)\n\
59        }}",
60        func_name
61    );
62
63    // Parse the trampoline string into a token stream.
64    let trampoline = syn::parse_str::<TokenStream2>(trampoline.as_str()).unwrap();
65
66    // Output the trampoline followed by the original main function.
67    quote! {
68        #trampoline
69        #main_func
70    }
71    .into()
72}
73
74/// Mark a function as the handler function of an IRQ.
75///
76/// A handler function should satisfy the following signature requirements:
77/// - Has no argument.
78/// - Returns `()`.
79/// - Is not `async`.
80/// - Is not variadic.
81///
82/// Example:
83/// ```rust
84/// #[handler(TIM2)]
85/// fn tim2_handler() {
86///     /* handler logic */
87/// }
88/// ```
89///
90/// The macro works by generating an assembly entry sequence and a trampoline
91/// function for the IRQ to call the user defined handler function. For example,
92/// for `TIM2`, the generated entry sequence and trampoline looks like below:
93///
94/// ```rust
95/// #[naked]
96/// #[export_name = "TIM2"]
97/// unsafe extern "C" fn __hopter_tim2_entry() {
98///     core::arch::asm!(
99///         // Preserve the task local storage (TLS) fields and exception return value.
100///         "ldr   r0, ={tls_mem_addr}",
101///         "ldmia r0!, {{r1-r3}}",
102///         "push  {{r1-r3, lr}}",
103///         // Set the kernel stacklet boundary and clear out other fields in the TLS.
104///         "ldr   r0, ={tls_mem_addr}",
105///         "ldr   r1, ={cont_stk_boundary}",
106///         "movs  r2, #0",
107///         "str   r1, [r0]",
108///         "str   r2, [r0, #4]",
109///         "str   r2, [r0, #8]",
110///         // Run the IRQ handler.
111///         "bl    {handler_trampoline}",
112///         // Restore the TLS fields and exception return value.
113///         "pop   {{r1-r3}}",
114///         "ldr   r0, ={tls_mem_addr}",
115///         "stmia r0!, {{r1-r3}}",
116///         // Exception return.
117///         "pop   {{pc}}",
118///         tls_mem_addr = const hopter::config::__TLS_MEM_ADDR,
119///         cont_stk_boundary = const hopter::config::__CONTIGUOUS_STACK_BOUNDARY,
120///         handler_trampoline = sym __hopter_tim2_trampoline,
121///         options(noreturn)
122///     )
123/// }
124///
125/// unsafe extern "C" fn __hopter_tim2_trampoline() {
126///     let prev_is_handler_unwinding
127///         = hopter::unwind::unwind::save_and_clear_isr_unwinding();
128///     let _ = hopter::unwind::unw_catch::catch_unwind(tim2_handler);
129///     hopter::unwind::unwind::set_isr_unwinding(prev_is_handler_unwinding);
130/// }
131/// ```
132#[cfg(feature = "armv6m")]
133#[proc_macro_attribute]
134pub fn handler(attr: TokenStream, item: TokenStream) -> TokenStream {
135    // Parse the `item` TokenStream into a Rust function.
136    let handler_func = parse_macro_input!(item as ItemFn);
137
138    // Parse the `attr` TokenStream into attribute arguments.
139    let attr_args = parse_macro_input!(attr as AttributeArgs);
140
141    check_handler_function_signature(&handler_func.sig);
142
143    let irq = parse_attribute_arg_to_irq(&attr_args);
144    let lower_caes_irq = irq.to_lowercase();
145
146    // Store the handler function's name.
147    let func_name = handler_func.sig.ident.to_string();
148
149    let entry_asm = format!(
150        "\
151        #[naked]\n\
152        #[export_name = \"{}\"]\n\
153        unsafe extern \"C\" fn __hopter_{}_entry() {{\n\
154            core::arch::asm!(\n\
155                \"ldr   r0, ={{tls_mem_addr}}\",\n\
156                \"ldmia r0!, {{{{r1-r3}}}}\",\n\
157                \"push  {{{{r1-r3, lr}}}}\",\n\
158                \"ldr   r0, ={{tls_mem_addr}}\",\n\
159                \"ldr   r1, ={{cont_stk_boundary}}\",\n\
160                \"movs  r2, #0\",\n\
161                \"str   r1, [r0]\",\n\
162                \"str   r2, [r0, #4]\",\n\
163                \"str   r2, [r0, #8]\",\n\
164                // Run the IRQ handler.\n\
165                \"bl    {{handler_trampoline}}\",\n\
166                \"pop   {{{{r1-r3}}}}\",\n\
167                \"ldr   r0, ={{tls_mem_addr}}\",\n\
168                \"stmia r0!, {{{{r1-r3}}}}\",\n\
169                // Exception return.\n\
170                \"pop   {{{{pc}}}}\",\n\
171                tls_mem_addr = const hopter::config::__TLS_MEM_ADDR,\n\
172                cont_stk_boundary = const hopter::config::__CONTIGUOUS_STACK_BOUNDARY,\n\
173                handler_trampoline = sym __hopter_{}_trampoline,\n\
174                options(noreturn)\n\
175            )\n\
176        }}\n\
177        ",
178        irq, lower_caes_irq, lower_caes_irq,
179    );
180
181    let entry_asm = syn::parse_str::<TokenStream2>(entry_asm.as_str()).unwrap();
182
183    let trampoline = format!(
184        "\
185        unsafe extern \"C\" fn __hopter_{}_trampoline() {{\n\
186        let prev_is_handler_unwinding = hopter::unwind::unwind::save_and_clear_isr_unwinding();\n\
187        let _ = hopter::unwind::unw_catch::catch_unwind({});\n\
188        hopter::unwind::unwind::set_isr_unwinding(prev_is_handler_unwinding);\n\
189        }}\n\
190        ",
191        lower_caes_irq, func_name,
192    );
193
194    // Parse the trampoline string into a token stream.
195    let trampoline = syn::parse_str::<TokenStream2>(trampoline.as_str()).unwrap();
196
197    // Output the trampoline followed by the original main function.
198    quote! {
199        #entry_asm
200        #trampoline
201        #handler_func
202    }
203    .into()
204}
205
206/// Mark a function as the handler function of an IRQ.
207///
208/// A handler function should satisfy the following signature requirements:
209/// - Has no argument.
210/// - Returns `()`.
211/// - Is not `async`.
212/// - Is not variadic.
213///
214/// Example:
215/// ```rust
216/// #[handler(TIM2)]
217/// fn tim2_handler() {
218///     /* handler logic */
219/// }
220/// ```
221///
222/// The macro works by generating an assembly entry sequence and a trampoline
223/// function for the IRQ to call the user defined handler function. For example,
224/// for `TIM2`, the generated entry sequence and trampoline looks like below:
225///
226/// ```rust
227/// #[naked]
228/// #[export_name = "TIM2"]
229/// unsafe extern "C" fn __hopter_tim2_entry() {
230///     core::arch::asm!(
231///         // Preserve the task local storage (TLS) fields and exception return value.
232///         "ldr   r0, ={tls_mem_addr}",
233///         "ldmia r0, {{r1-r3}}",
234///         "push  {{r1-r3, lr}}",
235///         // Set the kernel stacklet boundary and clear out other fields in the TLS.
236///         "ldr   r1, ={cont_stk_boundary}",
237///         "mov   r2, #0",
238///         "strd  r1, r2, [r0]",
239///         "str   r2, [r0, #8]",
240///         // Run the IRQ handler.
241///         "bl    {handler_trampoline}",
242///         // Restore the TLS fields and exception return value.
243///         "pop   {{r1-r3}}",
244///         "ldr   r0, ={tls_mem_addr}",
245///         "stmia r0, {{r1-r3}}",
246///         // Exception return.
247///         "pop   {{pc}}",
248///         tls_mem_addr = const hopter::config::__TLS_MEM_ADDR,
249///         cont_stk_boundary = const hopter::config::__CONTIGUOUS_STACK_BOUNDARY,
250///         handler_trampoline = sym __hopter_tim2_trampoline,
251///         options(noreturn)
252///     )
253/// }
254///
255/// unsafe extern "C" fn __hopter_tim2_trampoline() {
256///     let prev_is_handler_unwinding
257///         = hopter::unwind::unwind::save_and_clear_isr_unwinding();
258///     let _ = hopter::unwind::unw_catch::catch_unwind(tim2_handler);
259///     hopter::unwind::unwind::set_isr_unwinding(prev_is_handler_unwinding);
260/// }
261/// ```
262#[cfg(not(feature = "armv6m"))]
263#[proc_macro_attribute]
264pub fn handler(attr: TokenStream, item: TokenStream) -> TokenStream {
265    // Parse the `item` TokenStream into a Rust function.
266    let handler_func = parse_macro_input!(item as ItemFn);
267
268    // Parse the `attr` TokenStream into attribute arguments.
269    let attr_args = parse_macro_input!(attr as AttributeArgs);
270
271    check_handler_function_signature(&handler_func.sig);
272
273    let irq = parse_attribute_arg_to_irq(&attr_args);
274    let lower_caes_irq = irq.to_lowercase();
275
276    // Store the handler function's name.
277    let func_name = handler_func.sig.ident.to_string();
278
279    let entry_asm = format!(
280        "\
281        #[naked]\n\
282        #[export_name = \"{}\"]\n\
283        unsafe extern \"C\" fn __hopter_{}_entry() {{\n\
284            core::arch::asm!(\n\
285                \"ldr   r0, ={{tls_mem_addr}}\",\n\
286                \"ldmia r0, {{{{r1-r3}}}}\",\n\
287                \"push  {{{{r1-r3, lr}}}}\",\n\
288                \"ldr   r1, ={{cont_stk_boundary}}\",\n\
289                \"mov   r2, #0\",\n\
290                \"strd  r1, r2, [r0]\",\n\
291                \"str   r2, [r0, #8]\",\n\
292                // Run the IRQ handler.\n\
293                \"bl    {{handler_trampoline}}\",\n\
294                \"pop   {{{{r1-r3}}}}\",\n\
295                \"ldr   r0, ={{tls_mem_addr}}\",\n\
296                \"stmia r0, {{{{r1-r3}}}}\",\n\
297                // Exception return.\n\
298                \"pop   {{{{pc}}}}\",\n\
299                tls_mem_addr = const hopter::config::__TLS_MEM_ADDR,\n\
300                cont_stk_boundary = const hopter::config::__CONTIGUOUS_STACK_BOUNDARY,\n\
301                handler_trampoline = sym __hopter_{}_trampoline,\n\
302                options(noreturn)\n\
303            )\n\
304        }}\n\
305        ",
306        irq, lower_caes_irq, lower_caes_irq,
307    );
308
309    let entry_asm = syn::parse_str::<TokenStream2>(entry_asm.as_str()).unwrap();
310
311    let trampoline = format!(
312        "\
313        unsafe extern \"C\" fn __hopter_{}_trampoline() {{\n\
314        let prev_is_handler_unwinding = hopter::unwind::unwind::save_and_clear_isr_unwinding();\n\
315        let _ = hopter::unwind::unw_catch::catch_unwind({});\n\
316        hopter::unwind::unwind::set_isr_unwinding(prev_is_handler_unwinding);\n\
317        }}\n\
318        ",
319        lower_caes_irq, func_name,
320    );
321
322    // Parse the trampoline string into a token stream.
323    let trampoline = syn::parse_str::<TokenStream2>(trampoline.as_str()).unwrap();
324
325    // Output the trampoline followed by the original main function.
326    quote! {
327        #entry_asm
328        #trampoline
329        #handler_func
330    }
331    .into()
332}
333
334macro_rules! hander_macro_arg_error {
335    () => {
336        "Handler's argument must be one of the supported IRQs. Forgot to set the MCU model feature?"
337    };
338}
339
340macro_rules! hander_macro_retval_error {
341    () => {
342        "Handler's return type must be ()."
343    };
344}
345
346/// The main function should satisfy the following signature requirements:
347/// - Has one and only one argument of type `cortex_m::Peripherals`.
348/// - Returns `()` or `!`.
349/// - Is not `async`.
350/// - Is not `unsafe`.
351/// - Is not variadic.
352fn check_main_function_signature(sig: &Signature) {
353    if sig.inputs.iter().count() != 1 {
354        panic!("Main function must receive one argument of type `cortex_m::Peripherals`.");
355    }
356
357    match &sig.output {
358        // No return type specification.
359        ReturnType::Default => {}
360        // Specified return type as `-> ()`.
361        ReturnType::Type(_, b) => match &**b {
362            Type::Tuple(t) => {
363                if t.elems.len() != 0 {
364                    panic!(hander_macro_retval_error!());
365                }
366            }
367            Type::Never(_) => {}
368            _ => panic!(hander_macro_retval_error!()),
369        },
370    }
371
372    if sig.asyncness.is_some() {
373        panic!("Main function cannot be `async`.");
374    }
375
376    if sig.unsafety.is_some() {
377        panic!("Main function must be safe.");
378    }
379
380    if sig.variadic.is_some() {
381        panic!("Handler function cannot be variadic.");
382    }
383}
384
385/// A handler function should satisfy the following signature requirements:
386/// - Has no argument.
387/// - Returns `()`.
388/// - Is not `async`.
389/// - Is not variadic.
390fn check_handler_function_signature(sig: &Signature) {
391    if sig.inputs.iter().count() != 0 {
392        panic!("Handler function should not have any parameter.");
393    }
394
395    match &sig.output {
396        // No return type specification.
397        ReturnType::Default => {}
398        // Specified return type as `-> ()`.
399        ReturnType::Type(_, b) => match &**b {
400            Type::Tuple(t) => {
401                if t.elems.len() != 0 {
402                    panic!(hander_macro_retval_error!());
403                }
404            }
405            _ => panic!(hander_macro_retval_error!()),
406        },
407    }
408
409    if sig.abi.is_some() {
410        panic!("Handler function must have Rust ABI.");
411    }
412
413    if sig.asyncness.is_some() {
414        panic!("Handler function cannot be `async`.");
415    }
416
417    if sig.variadic.is_some() {
418        panic!("Handler function cannot be variadic.");
419    }
420}
421
422/// The handler attribute should contain one and only one argument, which is
423/// a supported IRQ name.
424fn parse_attribute_arg_to_irq(attr_args: &[NestedMeta]) -> String {
425    // Check that there is only one attribute argument.
426    if attr_args.len() != 1 {
427        panic!(hander_macro_arg_error!());
428    }
429
430    // Convert the argument into a string.
431    let arg = match attr_args.first().unwrap() {
432        NestedMeta::Meta(Meta::Path(ss)) => quote! { #ss }.to_string(),
433        _ => panic!(hander_macro_arg_error!()),
434    };
435
436    // Verify that the string names one of the supported IRQs.
437    if !SUPPORTED_IRQS.iter().any(|irq| irq == &arg) {
438        panic!(hander_macro_arg_error!());
439    }
440
441    arg
442}
443
444#[cfg(any(
445    feature = "stm32f401",
446    feature = "stm32f405",
447    feature = "stm32f407",
448    feature = "stm32f410",
449    feature = "stm32f411",
450    feature = "stm32f412",
451    feature = "stm32f413",
452    feature = "stm32f427",
453    feature = "stm32f429",
454    feature = "stm32f446",
455    feature = "stm32f469",
456))]
457mod stm32f4;
458
459#[cfg(any(
460    feature = "stm32f401",
461    feature = "stm32f405",
462    feature = "stm32f407",
463    feature = "stm32f410",
464    feature = "stm32f411",
465    feature = "stm32f412",
466    feature = "stm32f413",
467    feature = "stm32f427",
468    feature = "stm32f429",
469    feature = "stm32f446",
470    feature = "stm32f469",
471))]
472use stm32f4::SUPPORTED_IRQS;
473
474#[cfg(any(
475    feature = "stm32f030",
476    feature = "stm32f030x4",
477    feature = "stm32f030x6",
478    feature = "stm32f030x8",
479    feature = "stm32f030xc",
480    feature = "stm32f031",
481    feature = "stm32f038",
482    feature = "stm32f042",
483    feature = "stm32f048",
484    feature = "stm32f051",
485    feature = "stm32f058",
486    feature = "stm32f070",
487    feature = "stm32f070x6",
488    feature = "stm32f070xb",
489    feature = "stm32f071",
490    feature = "stm32f072",
491    feature = "stm32f078",
492    feature = "stm32f091",
493    feature = "stm32f098",
494))]
495mod stm32f0;
496
497#[cfg(any(
498    feature = "stm32f030",
499    feature = "stm32f030x4",
500    feature = "stm32f030x6",
501    feature = "stm32f030x8",
502    feature = "stm32f030xc",
503    feature = "stm32f031",
504    feature = "stm32f038",
505    feature = "stm32f042",
506    feature = "stm32f048",
507    feature = "stm32f051",
508    feature = "stm32f058",
509    feature = "stm32f070",
510    feature = "stm32f070x6",
511    feature = "stm32f070xb",
512    feature = "stm32f071",
513    feature = "stm32f072",
514    feature = "stm32f078",
515    feature = "stm32f091",
516    feature = "stm32f098",
517))]
518use stm32f0::SUPPORTED_IRQS;
519
520#[cfg(not(any(
521    feature = "stm32f401",
522    feature = "stm32f405",
523    feature = "stm32f407",
524    feature = "stm32f410",
525    feature = "stm32f411",
526    feature = "stm32f412",
527    feature = "stm32f413",
528    feature = "stm32f427",
529    feature = "stm32f429",
530    feature = "stm32f446",
531    feature = "stm32f469",
532    feature = "stm32f030",
533    feature = "stm32f030x4",
534    feature = "stm32f030x6",
535    feature = "stm32f030x8",
536    feature = "stm32f030xc",
537    feature = "stm32f031",
538    feature = "stm32f038",
539    feature = "stm32f042",
540    feature = "stm32f048",
541    feature = "stm32f051",
542    feature = "stm32f058",
543    feature = "stm32f070",
544    feature = "stm32f070x6",
545    feature = "stm32f070xb",
546    feature = "stm32f071",
547    feature = "stm32f072",
548    feature = "stm32f078",
549    feature = "stm32f091",
550    feature = "stm32f098",
551)))]
552const SUPPORTED_IRQS: [&str; 0] = [];