Debian Codegraph @

debian/rust-vendor/defmt-macros/src/attributes/panic_handler.rs

raw
1 use proc_macro::TokenStream;
2 use proc_macro2::Span;
3 use quote::quote;
4 use syn::{parse_macro_input, spanned::Spanned, Attribute, ItemFn, ReturnType, Type};
5
6 pub(crate) fn expand(args: TokenStream, item: TokenStream) -> TokenStream {
7 let fun = parse_macro_input!(item as ItemFn);
8
9 if !args.is_empty() {
10 return syn::Error::new(
11 Span::call_site(),
12 "`#[defmt::panic_handler]` attribute takes no arguments",
13 )
14 .into_compile_error()
15 .into();
16 }
17
18 if let Err(err) = validate(&fun) {
19 return err.into_compile_error().into();
20 };
21
22 codegen(&fun)
23 }
24
25 fn validate(fun: &ItemFn) -> syn::Result<()> {
26 let is_divergent = match &fun.sig.output {
27 ReturnType::Default => false,
28 ReturnType::Type(_, ty) => matches!(&**ty, Type::Never(_)),
29 };
30
31 if fun.sig.constness.is_some()
32 || fun.sig.asyncness.is_some()
33 || fun.sig.unsafety.is_some()
34 || fun.sig.abi.is_some()
35 || !fun.sig.generics.params.is_empty()
36 || fun.sig.generics.where_clause.is_some()
37 || fun.sig.variadic.is_some()
38 || !fun.sig.inputs.is_empty()
39 || !is_divergent
40 {
41 return Err(syn::Error::new(
42 fun.sig.ident.span(),
43 "function must have signature `fn() -> !`",
44 ));
45 }
46
47 check_for_attribute_conflicts("panic_handler", &fun.attrs, &["export_name", "no_mangle"])
48 }
49
50 /// Checks if any attribute in `attrs_to_check` is in `reject_list` and returns a compiler error if there's a match
51 ///
52 /// The compiler error will indicate that the attribute conflicts with `attr_name`
53 fn check_for_attribute_conflicts(
54 attr_name: &str,
55 attrs_to_check: &[Attribute],
56 reject_list: &[&str],
57 ) -> syn::Result<()> {
58 for attr in attrs_to_check {
59 if let Some(ident) = attr.path().get_ident() {
60 let ident = ident.to_string();
61
62 if reject_list.contains(&ident.as_str()) {
63 return Err(syn::Error::new(
64 attr.span(),
65 format!(
66 "`#[{}]` attribute cannot be used together with `#[{}]`",
67 attr_name, ident
68 ),
69 ));
70 }
71 }
72 }
73 Ok(())
74 }
75
76 fn codegen(fun: &ItemFn) -> TokenStream {
77 let attrs = &fun.attrs;
78 let block = &fun.block;
79 let ident = &fun.sig.ident;
80
81 quote!(
82 #(#attrs)*
83 #[export_name = "_defmt_panic"]
84 #[inline(never)]
85 fn #ident() -> ! {
86 #block
87 }
88 )
89 .into()
90 }