1 // Copyright 2025 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 use proc_macro::TokenStream;
16 use quote::{format_ident, quote};
17 use syn::{parse_macro_input, ItemFn};
18
19 #[proc_macro_attribute]
test(_attr: TokenStream, item: TokenStream) -> TokenStream20 pub fn test(_attr: TokenStream, item: TokenStream) -> TokenStream {
21 let item: ItemFn = parse_macro_input!(item as ItemFn);
22 let fn_ident = item.sig.ident.clone();
23 let fn_name = item.sig.ident.to_string();
24 let ctor_fn_ident = format_ident!("__mz_unittest_ctor_fn_{}__", fn_name);
25 let ctor_ident = format_ident!("__mz_unittest_ctor_{}__", fn_name);
26 let desc_ident = format_ident!("__MZ_UNITTEST_DESC_{}__", fn_name.to_uppercase());
27 quote! {
28 static mut #desc_ident: unittest::TestDescAndFn = unittest::TestDescAndFn::new(
29 unittest::TestDesc{
30 name: #fn_name,
31 },
32 unittest::TestFn::StaticTestFn(#fn_ident),
33 );
34
35 extern "C" fn #ctor_fn_ident() -> usize {
36 use core::ptr::addr_of_mut;
37 // Safety: We're only ever mutating this at constructor time which
38 // is single threaded.
39 let desc = unsafe { addr_of_mut!(#desc_ident).as_mut().unwrap_unchecked() };
40 unittest::add_test(desc);
41 0
42 }
43
44 #[used]
45 #[cfg_attr(target_os = "linux", link_section = ".init_array")]
46 #[cfg_attr(target_os = "none", link_section = ".init_array")]
47 #[cfg_attr(target_vendor = "apple", link_section = "__DATA,__mod_init_func")]
48 #[cfg_attr(windows, link_section = ".CRT$XCU")]
49 static #ctor_ident: extern "C" fn() -> usize = #ctor_fn_ident;
50
51 #item
52 }
53 .into()
54 }
55