-
Notifications
You must be signed in to change notification settings - Fork 1.5k
wasmtime: Introduce the test-macros
crate
#8622
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
alexcrichton
merged 6 commits into
bytecodealliance:main
from
saulecabrera:add-test-macros
May 28, 2024
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
bb155c4
wasmtime: Introduce the `test-macros` crate
saulecabrera 61cde97
Add crate license
saulecabrera 222363e
Clippy fixes
saulecabrera 0a31af9
Remove test-macros from members
saulecabrera 49cbac0
Clean up test-macros Cargo.toml
saulecabrera 0bc9a6a
Add `TestConfig` and simpify parsing
saulecabrera File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
[package] | ||
description = "Macros for testing Wasmtime" | ||
name = "wasmtime-test-macros" | ||
license = "Apache-2.0 WITH LLVM-exception" | ||
version = "0.0.0" | ||
authors.workspace = true | ||
edition.workspace = true | ||
rust-version.workspace = true | ||
publish = false | ||
|
||
[lib] | ||
proc-macro = true | ||
test = false | ||
doctest = false | ||
|
||
[lints] | ||
workspace = true | ||
|
||
[dependencies] | ||
quote = "1.0" | ||
proc-macro2 = "1.0" | ||
syn = { workspace = true, features = ["full"] } | ||
anyhow = { workspace = true } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,178 @@ | ||
//! Wasmtime test macro. | ||
//! | ||
//! This macro is a helper to define tests that exercise multiple configuration | ||
//! combinations for Wasmtime. Currently, only compiler strategies are | ||
//! supported. | ||
//! | ||
//! Usage | ||
//! | ||
//! #[wasmtime_test(strategies(Cranelift, Winch))] | ||
//! fn my_test(config: &mut Config) -> Result<()> { | ||
//! Ok(()) | ||
//! } | ||
use proc_macro::TokenStream; | ||
use quote::{quote, ToTokens, TokenStreamExt}; | ||
use syn::{ | ||
braced, | ||
parse::{Parse, ParseStream}, | ||
parse_macro_input, token, Attribute, Ident, Result, ReturnType, Signature, Visibility, | ||
}; | ||
|
||
/// Test configuration. | ||
struct TestConfig { | ||
/// Supported compiler strategies. | ||
strategies: Vec<(String, Ident)>, | ||
} | ||
|
||
impl TestConfig { | ||
/// Validate the test configuration. | ||
/// Only the number of strategies is validated, as this avoid expansions of | ||
/// empty strategies or more strategies than supported. | ||
/// | ||
/// The supported strategies are validated inline when parsing. | ||
fn validate(&self) -> anyhow::Result<()> { | ||
if self.strategies.len() > 2 { | ||
Err(anyhow::anyhow!("Expected at most 2 strategies")) | ||
} else if self.strategies.len() == 0 { | ||
Err(anyhow::anyhow!("Expected at least 1 strategy")) | ||
} else { | ||
Ok(()) | ||
} | ||
} | ||
} | ||
|
||
impl Default for TestConfig { | ||
fn default() -> Self { | ||
Self { strategies: vec![] } | ||
} | ||
} | ||
|
||
/// A generic function body represented as a braced [`TokenStream`]. | ||
struct Block { | ||
brace: token::Brace, | ||
rest: proc_macro2::TokenStream, | ||
} | ||
|
||
impl Parse for Block { | ||
fn parse(input: ParseStream) -> Result<Self> { | ||
let content; | ||
Ok(Self { | ||
brace: braced!(content in input), | ||
rest: content.parse()?, | ||
}) | ||
} | ||
} | ||
|
||
impl ToTokens for Block { | ||
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { | ||
self.brace.surround(tokens, |tokens| { | ||
tokens.append_all(self.rest.clone()); | ||
}); | ||
} | ||
} | ||
|
||
/// Custom function parser. | ||
/// Parses the function's attributes, visibility and signature, leaving the | ||
/// block as an opaque [`TokenStream`]. | ||
struct Fn { | ||
attrs: Vec<Attribute>, | ||
visibility: Visibility, | ||
sig: Signature, | ||
body: Block, | ||
} | ||
|
||
impl Parse for Fn { | ||
fn parse(input: ParseStream) -> Result<Self> { | ||
let attrs = input.call(Attribute::parse_outer)?; | ||
let visibility: Visibility = input.parse()?; | ||
let sig: Signature = input.parse()?; | ||
let body: Block = input.parse()?; | ||
|
||
Ok(Self { | ||
attrs, | ||
visibility, | ||
sig, | ||
body, | ||
}) | ||
} | ||
} | ||
|
||
impl ToTokens for Fn { | ||
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { | ||
for attr in &self.attrs { | ||
attr.to_tokens(tokens); | ||
} | ||
self.visibility.to_tokens(tokens); | ||
self.sig.to_tokens(tokens); | ||
self.body.to_tokens(tokens); | ||
} | ||
} | ||
|
||
#[proc_macro_attribute] | ||
pub fn wasmtime_test(attrs: TokenStream, item: TokenStream) -> TokenStream { | ||
let mut test_config = TestConfig::default(); | ||
|
||
let config_parser = syn::meta::parser(|meta| { | ||
if meta.path.is_ident("strategies") { | ||
meta.parse_nested_meta(|meta| { | ||
if meta.path.is_ident("Winch") || meta.path.is_ident("Cranelift") { | ||
let id = meta.path.require_ident()?.clone(); | ||
test_config.strategies.push((id.to_string(), id)); | ||
Ok(()) | ||
} else { | ||
Err(meta.error("Unknown strategy")) | ||
} | ||
})?; | ||
|
||
test_config.validate().map_err(|e| meta.error(e)) | ||
} else { | ||
Err(meta.error("Unsupported attributes")) | ||
} | ||
}); | ||
|
||
parse_macro_input!(attrs with config_parser); | ||
|
||
match expand(&test_config, parse_macro_input!(item as Fn)) { | ||
Ok(tok) => tok, | ||
Err(e) => e.into_compile_error().into(), | ||
} | ||
} | ||
|
||
fn expand(test_config: &TestConfig, func: Fn) -> Result<TokenStream> { | ||
let mut tests = vec![quote! { #func }]; | ||
let attrs = &func.attrs; | ||
|
||
for (strategy_name, ident) in &test_config.strategies { | ||
// Winch currently only offers support for x64. | ||
let target = if strategy_name == "Winch" { | ||
quote! { #[cfg(target_arch = "x86_64")] } | ||
} else { | ||
quote! {} | ||
}; | ||
let func_name = &func.sig.ident; | ||
let ret = match &func.sig.output { | ||
ReturnType::Default => quote! { () }, | ||
ReturnType::Type(_, ty) => quote! { -> #ty }, | ||
}; | ||
let test_name = Ident::new( | ||
&format!("{}_{}", strategy_name.to_lowercase(), func_name), | ||
func_name.span(), | ||
); | ||
let tok = quote! { | ||
#[test] | ||
#target | ||
#(#attrs)* | ||
fn #test_name() #ret { | ||
let mut config = Config::new(); | ||
config.strategy(Strategy::#ident); | ||
#func_name(&mut config) | ||
} | ||
}; | ||
|
||
tests.push(tok); | ||
} | ||
Ok(quote! { | ||
#(#tests)* | ||
} | ||
.into()) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep, this is exactly what I was imagining usage would look like 👍