Skip to main content

axtest_macros/
lib.rs

1//! Procedural macros for the `axtest` runtime.
2//!
3//! This crate provides two attribute macros:
4//! - [`def_mod`] for declaring test modules with optional init/exit hooks.
5//! - [`axtest`] / [`def_test`] for registering test functions into the
6//!   linker-collected `.axtest_array` section.
7//!
8//! The generated descriptors are consumed by `axtest::init().run_tests()` at
9//! runtime.
10
11use proc_macro::TokenStream;
12use quote::quote;
13use syn::{Error, Ident, Item, ItemFn, ItemMod, LitStr, Meta, Token, punctuated::Punctuated};
14
15/// Define a test module that is only compiled under `cfg(axtest)`.
16///
17/// This macro should be applied to an inline module that may optionally define:
18/// - `fn axtest_init(sym: axtest::AxTestDescriptor)`
19/// - `fn axtest_exit(sym: axtest::AxTestDescriptor)`
20///
21/// If present, these hooks are invoked around each `#[def_test]` execution in
22/// the same module.
23///
24/// # Arguments
25///
26/// This attribute accepts no arguments.
27///
28/// # Errors
29///
30/// Emits a compile error if any attribute argument is provided.
31///
32/// # Example
33///
34/// ```rust,ignore
35/// use axtest_macros::{def_mod, def_test};
36///
37/// #[def_mod]
38/// mod sample {
39///     fn axtest_init(_sym: axtest::AxTestDescriptor) {
40///         // per-test setup
41///     }
42///
43///     fn axtest_exit(_sym: axtest::AxTestDescriptor) {
44///         // per-test teardown
45///     }
46///
47///     #[def_test]
48///     fn smoke() {
49///         // test body
50///     }
51/// }
52/// ```
53#[proc_macro_attribute]
54pub fn def_mod(attr: TokenStream, item: TokenStream) -> TokenStream {
55    if !attr.is_empty() {
56        return Error::new(
57            proc_macro2::Span::call_site(),
58            "def_mod does not accept arguments",
59        )
60        .to_compile_error()
61        .into();
62    }
63
64    let mut item = syn::parse_macro_input!(item as ItemMod);
65
66    let (has_init, has_exit) = if let Some((_, items)) = &item.content {
67        let mut has_init = false;
68        let mut has_exit = false;
69        for it in items {
70            if let Item::Fn(func) = it {
71                if func.sig.ident == "axtest_init" {
72                    has_init = true;
73                } else if func.sig.ident == "axtest_exit" {
74                    has_exit = true;
75                }
76            }
77        }
78        (has_init, has_exit)
79    } else {
80        (false, false)
81    };
82
83    let init_hook = if has_init {
84        quote! { Some(axtest_init as fn(axtest::AxTestDescriptor)) }
85    } else {
86        quote! { None }
87    };
88    let exit_hook = if has_exit {
89        quote! { Some(axtest_exit as fn(axtest::AxTestDescriptor)) }
90    } else {
91        quote! { None }
92    };
93
94    if let Some((_, items)) = &mut item.content {
95        items.push(syn::parse_quote! {
96            #[used]
97            #[unsafe(link_section = ".axtest_mod_hooks")]
98            #[allow(non_upper_case_globals)]
99            static __axtest_mod_hooks: axtest::AxTestModHookDescriptor =
100                axtest::AxTestModHookDescriptor::new(module_path!(), #init_hook, #exit_hook);
101        });
102    }
103
104    let expanded = quote! {
105        #[cfg(axtest)]
106        #item
107    };
108    expanded.into()
109}
110
111/// Define an axtest module and generate the kernel test entry point.
112///
113/// This macro accepts an inline module. Functions marked with Rust's standard
114/// `#[test]` attribute are registered as axtest cases, while the generated
115/// test target entry point runs the common axtest kernel runner.
116///
117/// An optional `setup = path::to::function` argument runs target-owned
118/// initialization once before the first test case.
119#[proc_macro_attribute]
120pub fn tests(attr: TokenStream, item: TokenStream) -> TokenStream {
121    match expand_tests_module(attr.into(), item.into()) {
122        Ok(expanded) => expanded.into(),
123        Err(err) => err.to_compile_error().into(),
124    }
125}
126
127/// Define and register a test case for the `axtest` runtime.
128///
129/// This macro expands a function into:
130/// - a static [`axtest::AxTestDescriptor`] placed in linker section `.axtest`,
131/// - a wrapped test function that optionally calls module-level init/exit hooks.
132///
133/// The function can either:
134/// - return `axtest::AxTestResult`, or
135/// - return nothing, in which case `AxTestResult::Ok` is appended automatically.
136///
137/// Existing attributes on the function are preserved. Special handling:
138/// - `#[ignore]` or `#[ignore = "reason"]` marks the case as ignored.
139/// - `#[should_panic]` marks the case as expected-failure.
140///
141/// # Arguments
142///
143/// Supported macro arguments:
144/// - `standard`: force standard execution mode.
145/// - `custom = "name"`: bind this case to a named custom executor.
146///
147/// Without arguments, mode defaults to `standard` unless `#[ignore]` is set.
148///
149/// # Errors
150///
151/// Emits a compile error when:
152/// - an unsupported argument is used,
153/// - `custom` is provided without a string literal.
154///
155/// # Examples
156///
157/// Basic test:
158/// ```rust,ignore
159/// use axtest_macros::def_test;
160///
161/// #[def_test]
162/// fn simple_case() {
163///     // no explicit return needed
164/// }
165/// ```
166///
167/// Custom executor test:
168/// ```rust,ignore
169/// use axtest_macros::def_test;
170///
171/// #[def_test(custom = "thread")]
172/// fn thread_case() -> axtest::AxTestResult {
173///     axtest::AxTestResult::Ok
174/// }
175/// ```
176///
177/// Ignored test with reason:
178/// ```rust,ignore
179/// use axtest_macros::def_test;
180///
181/// #[def_test]
182/// #[ignore = "depends on external device"]
183/// fn hw_dependent_case() {}
184/// ```
185#[proc_macro_attribute]
186pub fn axtest(attr: TokenStream, item: TokenStream) -> TokenStream {
187    expand_axtest(attr, item)
188}
189
190#[proc_macro_attribute]
191pub fn def_test(attr: TokenStream, item: TokenStream) -> TokenStream {
192    expand_axtest(attr, item)
193}
194
195fn expand_axtest(attr: TokenStream, item: TokenStream) -> TokenStream {
196    let item = syn::parse_macro_input!(item as ItemFn);
197    let args = syn::parse_macro_input!(attr with Punctuated::<Meta, Token![,]>::parse_terminated);
198
199    let fn_name = &item.sig.ident;
200    let fn_attrs = &item.attrs;
201    let fn_stmts = &item.block.stmts;
202
203    // Analyzing the `#[ignore]` and `#[should_panic]` attributes
204    let mut should_panic = false;
205    let mut ignore = false;
206    let mut ignore_reason: Option<String> = None;
207
208    for attr in &item.attrs {
209        // Check #[ignore = "reason"] attribute
210        if attr.path().is_ident("ignore") {
211            ignore = true;
212            if let syn::Meta::NameValue(nv) = &attr.meta
213                && let syn::Expr::Lit(syn::ExprLit {
214                    lit: syn::Lit::Str(s),
215                    ..
216                }) = &nv.value
217            {
218                ignore_reason = Some(s.value());
219            }
220        }
221        // Check #[should_panic(expected = "...")]
222        if attr.path().is_ident("should_panic") {
223            should_panic = true;
224            if let syn::Meta::NameValue(nv) = &attr.meta
225                && let syn::Expr::Lit(syn::ExprLit {
226                    lit: syn::Lit::Str(_),
227                    ..
228                }) = &nv.value
229            {
230                // should_panic_expected = s.value();
231            }
232        }
233    }
234
235    // Check if function returns TestResult
236    let has_return_type = !matches!(item.sig.output, syn::ReturnType::Default);
237
238    let mut execution_mode = if ignore {
239        quote!(axtest::AxTestExecutionMode::Ignore)
240    } else {
241        quote!(axtest::AxTestExecutionMode::Standard)
242    };
243    let mut executor_name = String::new();
244
245    for arg in args {
246        match arg {
247            Meta::Path(path) if path.is_ident("standard") => {
248                execution_mode = quote!(axtest::AxTestExecutionMode::Standard);
249            }
250            Meta::NameValue(nv) if nv.path.is_ident("custom") => {
251                let lit = match nv.value {
252                    syn::Expr::Lit(syn::ExprLit {
253                        lit: syn::Lit::Str(s),
254                        ..
255                    }) => s,
256                    _ => {
257                        return Error::new_spanned(nv, "`custom` expects a string literal")
258                            .to_compile_error()
259                            .into();
260                    }
261                };
262                executor_name = lit.value();
263                execution_mode = quote!(axtest::AxTestExecutionMode::Custom);
264            }
265            other => {
266                return Error::new_spanned(
267                    other,
268                    "unsupported axtest argument, expected `standard` or `custom = \"name\"`",
269                )
270                .to_compile_error()
271                .into();
272            }
273        }
274    }
275
276    let ignore_reason_lit = ignore_reason.unwrap_or_else(|| "ignored".to_string());
277
278    // Generate a unique static name for the test descriptor
279    let static_name = Ident::new(&format!("__axtest_descriptor_{}", fn_name), fn_name.span());
280
281    let fn_name_str = fn_name.to_string();
282    let executor_name_lit = LitStr::new(&executor_name, proc_macro2::Span::call_site());
283    let expanded = if has_return_type {
284        quote! {
285            #[used]
286            #[unsafe(link_section = ".axtest_array")]
287            #[allow(non_upper_case_globals)]
288            static #static_name: axtest::AxTestDescriptor = axtest::AxTestDescriptor::new(
289                #fn_name_str,
290                module_path!(),
291                #fn_name,
292                #executor_name_lit,
293                #should_panic,
294                #ignore_reason_lit,
295                #execution_mode,
296            );
297
298            #(#fn_attrs)*
299            fn #fn_name() -> axtest::AxTestResult {
300                let __axtest_desc = #static_name;
301                axtest::call_module_init(module_path!(), __axtest_desc);
302                let __axtest_result = (|| -> axtest::AxTestResult {
303                    #(#fn_stmts)*
304                })();
305                axtest::call_module_exit(module_path!(), __axtest_desc);
306                __axtest_result
307            }
308        }
309    } else {
310        quote! {
311            #[used]
312            #[unsafe(link_section = ".axtest_array")]
313            #[allow(non_upper_case_globals)]
314            static #static_name: axtest::AxTestDescriptor = axtest::AxTestDescriptor::new(
315                #fn_name_str,
316                module_path!(),
317                #fn_name,
318                #executor_name_lit,
319                #should_panic,
320                #ignore_reason_lit,
321                #execution_mode,
322            );
323
324            #(#fn_attrs)*
325            fn #fn_name() -> axtest::AxTestResult {
326                let __axtest_desc = #static_name;
327                axtest::call_module_init(module_path!(), __axtest_desc);
328                let __axtest_result = (|| -> axtest::AxTestResult {
329                    #(#fn_stmts)*
330                    axtest::AxTestResult::Ok
331                })();
332                axtest::call_module_exit(module_path!(), __axtest_desc);
333                __axtest_result
334            }
335        }
336    };
337
338    expanded.into()
339}
340
341fn expand_tests_module(
342    attr: proc_macro2::TokenStream,
343    item: proc_macro2::TokenStream,
344) -> syn::Result<proc_macro2::TokenStream> {
345    let setup = if attr.is_empty() {
346        None
347    } else {
348        let meta: Meta = syn::parse2(attr)?;
349        match meta {
350            Meta::NameValue(value) if value.path.is_ident("setup") => match value.value {
351                syn::Expr::Path(path) if path.qself.is_none() => Some(path.path),
352                other => {
353                    return Err(Error::new_spanned(other, "`setup` expects a function path"));
354                }
355            },
356            other => {
357                return Err(Error::new_spanned(
358                    other,
359                    "unsupported tests argument, expected `setup = path::to::function`",
360                ));
361            }
362        }
363    };
364    let run_setup = setup.map(|setup| quote! { #setup(); });
365
366    let mut module: ItemMod = syn::parse2(item)?;
367    if module.content.is_none() {
368        return Err(Error::new_spanned(
369            &module,
370            "tests must be applied to an inline module",
371        ));
372    }
373    let (_, items) = module.content.as_mut().expect("inline module checked");
374
375    let old_items = core::mem::take(items);
376    let mut new_items = Vec::with_capacity(old_items.len());
377    for mut item in old_items {
378        if let Item::Fn(func) = &mut item
379            && has_attr(func, "test")
380        {
381            new_items.extend(expand_test_function(func)?);
382            continue;
383        }
384        new_items.push(item);
385    }
386    *items = new_items;
387
388    Ok(quote! {
389        #module
390
391        #[unsafe(no_mangle)]
392        fn main() {
393            fn __axtest_print(args: core::fmt::Arguments<'_>) {
394                ax_std::print!("{}", args);
395            }
396
397            fn __axtest_wait_for_coverage_extraction() {
398                const WAIT_NANOS: u64 = 30_000_000_000;
399                let start = ax_hal::time::wall_time_nanos();
400                while ax_hal::time::wall_time_nanos().saturating_sub(start) < WAIT_NANOS {
401                    core::hint::spin_loop();
402                }
403            }
404
405            #run_setup
406            axtest::run_kernel_tests(
407                axtest::KernelTestConfig::new(
408                    __axtest_print,
409                    ax_std::os::arceos::api::sys::ax_terminate,
410                )
411                    .with_coverage_wait(__axtest_wait_for_coverage_extraction),
412            );
413        }
414    })
415}
416
417fn has_attr(func: &ItemFn, name: &str) -> bool {
418    func.attrs.iter().any(|attr| attr.path().is_ident(name))
419}
420
421fn expand_test_function(func: &mut ItemFn) -> syn::Result<Vec<Item>> {
422    let fn_name = func.sig.ident.clone();
423    let fn_name_str = fn_name.to_string();
424    let has_return_type = !matches!(func.sig.output, syn::ReturnType::Default);
425    let fn_stmts = func.block.stmts.clone();
426    let vis = func.vis.clone();
427    let mut should_panic = false;
428    let mut ignore = false;
429    let mut ignore_reason: Option<String> = None;
430
431    func.attrs.retain(|attr| {
432        if attr.path().is_ident("test") {
433            return false;
434        }
435        if attr.path().is_ident("ignore") {
436            ignore = true;
437            if let syn::Meta::NameValue(nv) = &attr.meta
438                && let syn::Expr::Lit(syn::ExprLit {
439                    lit: syn::Lit::Str(s),
440                    ..
441                }) = &nv.value
442            {
443                ignore_reason = Some(s.value());
444            }
445            return false;
446        }
447        if attr.path().is_ident("should_panic") {
448            should_panic = true;
449            return false;
450        }
451        true
452    });
453    let fn_attrs = func.attrs.clone();
454
455    let ignore_reason_lit = ignore_reason.unwrap_or_else(|| "ignored".to_string());
456    let execution_mode = if ignore {
457        quote!(axtest::AxTestExecutionMode::Ignore)
458    } else {
459        quote!(axtest::AxTestExecutionMode::Standard)
460    };
461    let static_name = Ident::new(&format!("__axtest_descriptor_{}", fn_name), fn_name.span());
462
463    let wrapper = if has_return_type {
464        quote! {
465            #(#fn_attrs)*
466            #vis fn #fn_name() -> axtest::AxTestResult {
467                let __axtest_desc = #static_name;
468                axtest::call_module_init(module_path!(), __axtest_desc);
469                let __axtest_result = (|| -> axtest::AxTestResult {
470                    #(#fn_stmts)*
471                })();
472                axtest::call_module_exit(module_path!(), __axtest_desc);
473                __axtest_result
474            }
475        }
476    } else {
477        quote! {
478            #(#fn_attrs)*
479            #vis fn #fn_name() -> axtest::AxTestResult {
480                let __axtest_desc = #static_name;
481                axtest::call_module_init(module_path!(), __axtest_desc);
482                let __axtest_result = (|| -> axtest::AxTestResult {
483                    #(#fn_stmts)*
484                    axtest::AxTestResult::Ok
485                })();
486                axtest::call_module_exit(module_path!(), __axtest_desc);
487                __axtest_result
488            }
489        }
490    };
491
492    let file: syn::File = syn::parse2(quote! {
493        #[used]
494        #[unsafe(link_section = ".axtest_array")]
495        #[allow(non_upper_case_globals)]
496        static #static_name: axtest::AxTestDescriptor = axtest::AxTestDescriptor::new(
497            #fn_name_str,
498            module_path!(),
499            #fn_name,
500            "",
501            #should_panic,
502            #ignore_reason_lit,
503            #execution_mode,
504        );
505
506        #wrapper
507    })?;
508    Ok(file.items)
509}
510
511#[cfg(test)]
512mod tests {
513    use proc_macro2::TokenStream as TokenStream2;
514    use quote::quote;
515
516    #[test]
517    fn tests_module_generates_entry_and_descriptors() {
518        let input = quote! {
519            mod tests {
520                #[test]
521                fn smoke() {}
522
523                #[test]
524                #[ignore = "hardware only"]
525                fn ignored() {}
526            }
527        };
528
529        let expanded = super::expand_tests_module(TokenStream2::new(), input)
530            .expect("tests module should expand");
531        let expanded = expanded.to_string();
532
533        assert!(expanded.contains("fn main"));
534        assert!(expanded.contains("no_mangle"));
535        assert!(expanded.contains("run_kernel_tests"));
536        assert!(expanded.contains("__axtest_descriptor_smoke"));
537        assert!(expanded.contains("__axtest_descriptor_ignored"));
538        assert!(expanded.contains("hardware only"));
539    }
540
541    #[test]
542    fn tests_module_runs_target_setup_before_the_suite() {
543        let input = quote! { mod tests {} };
544        let attr = quote! { setup = init_kernel_test_services };
545
546        let expanded = super::expand_tests_module(attr, input)
547            .expect("tests module setup should expand")
548            .to_string();
549        let setup = expanded
550            .find("init_kernel_test_services ()")
551            .expect("generated entry should call target setup");
552        let run = expanded
553            .find("axtest :: run_kernel_tests")
554            .expect("generated entry should run the suite");
555
556        assert!(setup < run);
557    }
558}