esp-hal-procmacros 0.22.0

Procedural macros for esp-hal
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use std::{cell::RefCell, fmt::Display, thread};

use proc_macro2::{TokenStream, TokenStream as TokenStream2};
use quote::{ToTokens, quote};
use syn::{
    Attribute,
    Meta,
    ReturnType,
    Token,
    Type,
    parse::{Parse, ParseBuffer},
    punctuated::Punctuated,
};

/// Parsed arguments for the `main` macro.
pub struct Args {
    pub(crate) meta: Vec<Meta>,
}

impl Parse for Args {
    fn parse(input: &ParseBuffer) -> syn::Result<Self> {
        let meta = Punctuated::<Meta, Token![,]>::parse_terminated(input)?;
        Ok(Args {
            meta: meta.into_iter().collect(),
        })
    }
}

/// Procedural macro entry point for the async `main` function.
pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
    let args: Args = crate::unwrap_or_compile_error!(syn::parse2(args));
    let f: syn::ItemFn = crate::unwrap_or_compile_error!(syn::parse2(item));

    run(&args.meta, f, main_fn()).unwrap_or_else(|x| x)
}

/// Expands and validates the async `main` function into a task entry point.
pub fn run(
    _args: &[Meta],
    f: syn::ItemFn,
    main: TokenStream2,
) -> Result<TokenStream2, TokenStream2> {
    let fargs = f.sig.inputs.clone();

    let ctxt = Ctxt::new();

    if f.sig.asyncness.is_none() {
        ctxt.error_spanned_by(&f.sig, "main function must be async");
    }
    if !f.sig.generics.params.is_empty() {
        ctxt.error_spanned_by(&f.sig, "main function must not be generic");
    }
    if f.sig.generics.where_clause.is_some() {
        ctxt.error_spanned_by(&f.sig, "main function must not have `where` clauses");
    }
    if f.sig.abi.is_some() {
        ctxt.error_spanned_by(&f.sig, "main function must not have an ABI qualifier");
    }
    if f.sig.variadic.is_some() {
        ctxt.error_spanned_by(&f.sig, "main function must not be variadic");
    }
    match &f.sig.output {
        ReturnType::Default => {}
        ReturnType::Type(_, ty) => match &**ty {
            Type::Tuple(tuple) if tuple.elems.is_empty() => {}
            Type::Never(_) => {}
            _ => ctxt.error_spanned_by(
                &f.sig,
                "main function must either not return a value, return `()` or return `!`",
            ),
        },
    }

    if fargs.len() != 1 {
        ctxt.error_spanned_by(&f.sig, "main function must have 1 argument: the spawner.");
    }

    let fattrs = f.attrs;
    let lint_attrs: Vec<Attribute> = fattrs
        .clone()
        .into_iter()
        .filter(|item| {
            item.path().is_ident("deny")
                || item.path().is_ident("allow")
                || item.path().is_ident("warn")
        })
        .collect();

    ctxt.check()?;

    let f_body = f.block;
    let out = &f.sig.output;

    let result = quote! {
        #(#lint_attrs)*
        #[doc(hidden)]
        pub(crate) mod __main {
            use super::*;

            #[doc(hidden)]
            #(#fattrs)*
            #[::embassy_executor::task()]
            async fn __embassy_main(#fargs) #out {
                #f_body
            }

            #[doc(hidden)]
            unsafe fn __make_static<T>(t: &mut T) -> &'static mut T {
                ::core::mem::transmute(t)
            }

            #(#fattrs)*
            #main
        }
    };

    Ok(result)
}

/// A type to collect errors together and format them.
///
/// Dropping this object will cause a panic. It must be consumed using
/// `check`.
///
/// References can be shared since this type uses run-time exclusive mut
/// checking.
#[derive(Default)]
pub struct Ctxt {
    // The contents will be set to `None` during checking. This is so that checking can be
    // enforced.
    errors: RefCell<Option<Vec<syn::Error>>>,
}

impl Ctxt {
    /// Create a new context object.
    ///
    /// This object contains no errors, but will still trigger a panic if it
    /// is not `check`ed.
    pub fn new() -> Self {
        Ctxt {
            errors: RefCell::new(Some(Vec::new())),
        }
    }

    /// Add an error to the context object with a tokenenizable object.
    ///
    /// The object is used for spanning in error messages.
    pub fn error_spanned_by<A: ToTokens, T: Display>(&self, obj: A, msg: T) {
        self.errors
            .borrow_mut()
            .as_mut()
            .unwrap()
            // Curb monomorphization from generating too many identical methods.
            .push(syn::Error::new_spanned(obj.into_token_stream(), msg));
    }

    /// Consume this object, producing a formatted error string if there are
    /// errors.
    pub fn check(self) -> Result<(), TokenStream2> {
        let errors = self.errors.borrow_mut().take().unwrap();
        match errors.len() {
            0 => Ok(()),
            _ => Err(to_compile_errors(errors)),
        }
    }
}

fn to_compile_errors(errors: Vec<syn::Error>) -> TokenStream2 {
    let compile_errors = errors.iter().map(syn::Error::to_compile_error);
    quote!(#(#compile_errors)*)
}

impl Drop for Ctxt {
    fn drop(&mut self) {
        if !thread::panicking() && self.errors.borrow().is_some() {
            panic!("forgot to check for errors");
        }
    }
}

/// Generates the `main` function that initializes and runs the async executor.
pub fn main_fn() -> TokenStream2 {
    let root = match proc_macro_crate::crate_name("esp-hal") {
        Ok(proc_macro_crate::FoundCrate::Name(ref name)) => quote::format_ident!("{name}"),
        _ => quote::format_ident!("esp_hal"),
    };

    quote! {
        #[#root::main]
        fn main() -> ! {
            let mut executor = ::esp_rtos::embassy::Executor::new();
            let executor = unsafe { __make_static(&mut executor) };
            executor.run(|spawner| {
                spawner.spawn(__embassy_main(spawner).unwrap());
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic() {
        let result = main(
            quote::quote! {}.into(),
            quote::quote! {
                async fn foo(spawner: Spawner){}
            }
            .into(),
        );

        assert_eq!(
            result.to_string(),
            quote::quote! {
                #[doc(hidden)]
                pub (crate) mod __main {
                    use super::*;
                    #[doc(hidden)]
                    #[::embassy_executor::task()]
                    async fn __embassy_main (spawner : Spawner) {
                        { }
                    }

                    #[doc(hidden)]
                    unsafe fn __make_static < T > (t : & mut T) -> & 'static mut T {
                        ::core::mem::transmute(t)
                    }

                    #[esp_hal::main]
                    fn main () -> ! {
                        let mut executor = ::esp_rtos::embassy::Executor::new();
                        let executor = unsafe { __make_static (& mut executor) };
                        executor . run (| spawner | {
                            spawner.spawn(__embassy_main (spawner).unwrap());
                        })
                    }
                }
            }
            .to_string()
        );
    }

    #[test]
    fn test_non_async_fn() {
        let result = main(
            quote::quote! {}.into(),
            quote::quote! {
                fn foo(spawner: Spawner){}
            }
            .into(),
        );

        assert_eq!(
            result.to_string(),
            quote::quote! {
                ::core::compile_error!{ "main function must be async" }
            }
            .to_string()
        );
    }

    #[test]
    fn test_no_arg() {
        let result = main(
            quote::quote! {}.into(),
            quote::quote! {
                async fn foo(){}
            }
            .into(),
        );

        assert_eq!(
            result.to_string(),
            quote::quote! {
                ::core::compile_error!{ "main function must have 1 argument: the spawner." }
            }
            .to_string()
        );
    }

    #[test]
    fn test_not_generic() {
        let result = main(
            quote::quote! {}.into(),
            quote::quote! {
                async fn foo<S>(spawner: S){}
            }
            .into(),
        );

        assert_eq!(
            result.to_string(),
            quote::quote! {
                ::core::compile_error!{ "main function must not be generic" }
            }
            .to_string()
        );
    }

    #[test]
    fn test_not_abi() {
        let result = main(
            quote::quote! {}.into(),
            quote::quote! {
                async extern "C" fn foo(spawner: Spawner){}
            }
            .into(),
        );

        assert_eq!(
            result.to_string(),
            quote::quote! {
                ::core::compile_error!{ "main function must not have an ABI qualifier" }
            }
            .to_string()
        );
    }

    #[test]
    fn test_not_variadic() {
        let result = main(
            quote::quote! {}.into(),
            quote::quote! {
                async fn foo(spawner: ...){}
            }
            .into(),
        );

        assert_eq!(
            result.to_string(),
            quote::quote! {
                ::core::compile_error!{ "main function must not be variadic" }
                ::core::compile_error!{ "main function must have 1 argument: the spawner." }
            }
            .to_string()
        );
    }

    #[test]
    fn test_not_return_value() {
        let result = main(
            quote::quote! {}.into(),
            quote::quote! {
                async fn foo(spawner: Spawner) -> u32 {}
            }
            .into(),
        );

        assert_eq!(
            result.to_string(),
            quote::quote! {
                ::core::compile_error!{ "main function must either not return a value, return `()` or return `!`" }
            }
            .to_string()
        );
    }

    #[test]
    fn test_basic_return_never() {
        let result = main(
            quote::quote! {}.into(),
            quote::quote! {
                async fn foo(spawner: Spawner) -> ! {}
            }
            .into(),
        );

        assert_eq!(
            result.to_string(),
            quote::quote! {
                #[doc(hidden)]
                pub (crate) mod __main {
                    use super::*;
                    #[doc(hidden)]
                    #[::embassy_executor::task()]
                    async fn __embassy_main (spawner : Spawner) -> ! {
                        { }
                    }

                    #[doc(hidden)]
                    unsafe fn __make_static < T > (t : & mut T) -> & 'static mut T {
                        ::core::mem::transmute(t)
                    }

                    # [esp_hal::main]
                    fn main () -> ! {
                        let mut executor = ::esp_rtos::embassy::Executor::new();
                        let executor = unsafe { __make_static (& mut executor) };
                        executor.run (| spawner | {
                            spawner.spawn(__embassy_main (spawner).unwrap());
                        })
                    }
                }
            }
            .to_string()
        );
    }

    #[test]
    fn test_basic_return_tuple() {
        let result = main(
            quote::quote! {}.into(),
            quote::quote! {
                async fn foo(spawner: Spawner) -> () {}
            }
            .into(),
        );

        assert_eq!(
            result.to_string(),
            quote::quote! {
                #[doc(hidden)]
                pub (crate) mod __main {
                    use super::*;
                    #[doc(hidden)]
                    #[::embassy_executor::task()]
                    async fn __embassy_main (spawner : Spawner) -> () {
                        { }
                    }

                    #[doc(hidden)]
                    unsafe fn __make_static < T > (t : & mut T) -> & 'static mut T {
                        ::core::mem::transmute(t)
                    }

                    #[esp_hal::main]
                    fn main () -> ! {
                        let mut executor = ::esp_rtos::embassy::Executor::new();
                        let executor = unsafe { __make_static (& mut executor) };
                        executor.run (| spawner | {
                            spawner.spawn(__embassy_main (spawner).unwrap());
                        })
                    }
                }
            }
            .to_string()
        );
    }

    #[test]
    fn test_basic_propagate_lint_attrs() {
        let result = main(
            quote::quote! {}.into(),
            quote::quote! {
                #[allow(allowed)]
                #[deny(denied)]
                #[warn(warning)]
                #[ram]
                async fn foo(spawner: Spawner) -> () {}
            }
            .into(),
        );

        assert_eq!(
            result.to_string(),
            quote::quote! {
                #[allow(allowed)]
                #[deny(denied)]
                #[warn (warning)]
                #[doc(hidden)]
                pub (crate) mod __main {
                    use super::*;
                    #[doc(hidden)]
                    #[allow(allowed)]
                    #[deny(denied)]
                    #[warn (warning)]
                    #[ram]
                    #[::embassy_executor::task()]
                    async fn __embassy_main (spawner : Spawner) -> () {
                        { }
                    }

                    #[doc(hidden)]
                    unsafe fn __make_static < T > (t : & mut T) -> & 'static mut T {
                        ::core::mem::transmute(t)
                    }

                    #[allow(allowed)]
                    #[deny(denied)]
                    #[warn(warning)]
                    #[ram]
                    #[esp_hal::main]
                    fn main () -> ! {
                        let mut executor = ::esp_rtos::embassy::Executor::new();
                        let executor = unsafe { __make_static (& mut executor) };
                        executor.run (| spawner | {
                            spawner.spawn(__embassy_main (spawner).unwrap());
                        })
                    }
                }
            }
            .to_string()
        );
    }
}