1use proc_macro::TokenStream;
12use quote::quote;
13use syn::{Error, Ident, Item, ItemFn, ItemMod, LitStr, Meta, Token, punctuated::Punctuated};
14
15#[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#[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#[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 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 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 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 }
232 }
233 }
234
235 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 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}